Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - value of uninitialized vector<int>

I understand from the answer to this question that values of global/static uninitialized int will be 0. The answer to this one says that for vectors, the default constructor for the object type will be called.

I am unable to figure out - what happens when I have vector<int> v(10) in a local function. What is the default constructor for int? What if I have vector<int> v(10) declared globally?

What I am seeing is that vector<int> v(10) in a local function is resulting in variables being 0 - but I am not sure if that is just because of my compiler or is the fixed expected behaviour.

like image 786
anon Avatar asked Mar 07 '11 16:03

anon


People also ask

What is the default value of vector?

The default value of a vector is 0.

Are vectors initialized with 0?

Any other number can be used. A vector can be initialized with all zeros in three principal ways: A) use the initializer_list, B) use the assign() vector member function to an empty vector (or push_back()), or C) use int or float as the template parameter specialization for a vector of initially only default values.


1 Answers

The zero initialization is specified in the standard as default zero initialization/value initialization for builtin types, primarily to support just this type of case in template use.

Note that this behavior is different from a local variable such as int x; which leaves the value uninitialized (as in the C language that behavior is inherited from).

like image 51
Mark B Avatar answered Oct 07 '22 19:10

Mark B