can somebody please tell me the difference between the following two code snippets:
//Code snippet A: Compiles fine
int main()
{
if(int i = 2)
{
i = 2 + 3;
}
else
{
i = 0;
}
}
//Code Snippet B: Doesn't compile :(
int main()
{
if((int i = 2))
{
i = 2 + 3;
}
else
{
i = 0;
}
}
If you notice the diff is just an extra parenthesis at if statement. I am using g++ compiler.Error is "expected primary-expression before âintâ"
Section 6.4 of the C++ standard (draft n2914 of c++0x) has this to say about the format of if statements:
Selection statements choose one of several flows of control.
selection-statement:
if ( condition ) statement
if ( condition ) statement else statement
switch ( condition ) statement
condition:
expression
type-specifier-seq attribute-specifieropt declarator = initializer-clause
type-specifier-seq attribute-specifieropt declarator braced-init-list
That bit at the end means a condition can be either an expression or a decalarator-type construct.
And the minute the parser hits that second parenthesis, it becomes an expression, so no declarations allowed, I'm afraid.
The snippet:
if (int i = 2) { ... } else { ... }
is perfectly valid C++ in which the if section defines an integer i for the duration of the if/else and sets it to 2. It then uses that 2 as the input to the if (2 is always true, being non-zero).
The snippet if((int i = 2)) is no different syntactically to int x = (int i = 2;); if (x) which is not valid C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With