Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ standard: default "const T& value" in vector constructor for type 'int'

Tags:

c++

stl

explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );

vector<int> vec(10);
cout << "vec.size: " << vec.size() << endl;
for (vector<int>::const_iterator iter=vec.begin(); iter != vec.end(); ++iter)
{
    cout << *iter << endl;
}

Output from VS2010:

vec.size: 10
0
0
0
0
0
0
0
0
0
0

Question>: Based on the latest C++ standard, what is the default int value when we define an object of vector by using vectorObject(size_type)?

Here as you can see, VS2010 outputs 0 as the default int value. But I don't know whether or not this is required by C++ standard.

like image 891
q0987 Avatar asked Aug 09 '11 20:08

q0987


People also ask

What is the default type for a constant in C?

The default value of constant variables are zero. A program that demonstrates the declaration of constant variables in C using const keyword is given as follows.

When did C Get const?

According to ESR, const was added in the ANSI C Draft Proposed Standard. Eric Giguere's summary of ANSI C, dated 1987, confirms it.

What is const type in C?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.

What is const modifier in C?

The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed ( Which depends upon where const variables are stored, we may change the value of const variable by using pointer ).


1 Answers

Yes, this is the required behavior. T() for any numeric type T yields 0 (of type T, of course).

This is called value initialization, which for numeric types is the same as zero initialization.

like image 157
James McNellis Avatar answered Nov 15 '22 03:11

James McNellis