Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the C++ compiler [duplicate]

Possible Duplicate:
Most vexing parse: why doesn't A a(()); work?

I am having this simple C++ issue that is making me wanna restart my CS degree all over again trying to learn something this time. ;)

Why this code doesn't compile:

vector<int> v(int());
v.push_back(1);

while this other one compiles without a single warning

vector<int> v((int()));
v.push_back(1);

It's even hard to find a difference at all (extra parenthesis were added :P).

like image 671
Ernesto Carvajal Avatar asked Jan 24 '12 13:01

Ernesto Carvajal


2 Answers

It's called the most vexing parse.

vector<int> v(int());

Declares a function v that takes a function (taking no parameters returning an int) and returns a vector<int>. This is automatically "adjusted" to a function v that takes a pointer to a function (taking no parameters returning an int) and returns a vector<int>.

The extra pair of parentheses inhibits this interpretation as you can't place extra parentheses around parameter declarators in function declarations so (int()) can only be interpreted as an initializer for an object named v.

C++ has an explicit disambiguation rule that prefers to parse things (in this case int()) as declarators rather than expressions if it makes syntactic (but not necessarily semantic) sense.

like image 75
CB Bailey Avatar answered Nov 07 '22 16:11

CB Bailey


Indeed its a function declaration. See: http://www.gotw.ca/gotw/075.htm

like image 34
KasF Avatar answered Nov 07 '22 18:11

KasF