Why "constructor-way" of declaring variable in "for-loop" allowed but in "if-statement" not allowed?

Posted by PiotrNycz on Stack Overflow See other posts from Stack Overflow or by PiotrNycz
Published on 2012-09-29T21:32:15Z Indexed on 2012/09/29 21:37 UTC
Read the original article Hit count: 169

Consider this simple example:

/*1*/ int main() {
/*2*/   for (int i(7); i;){break;} 
/*3*/   if (int i(7)) {}
/*4*/ }

Why line-2 compiles just fine, whilst line-3 gives the error? This is little strange to me why if-statement is in this aspect treated worse than for-loop?

If this is compiler specific - I tested with gcc-4.5.1:

prog.cpp: In function 'int main()': prog.cpp:3:7: error: expected primary-expression before 'int' prog.cpp:3:7: error: expected ')' before 'int'

I was inspired by this question

[UPDATE]

I know this compiles just fine:

/*1*/ int main() {
/*2*/   for (int i = 7; i;){break;} 
/*3*/   if (int i = 7) {}
/*4*/ }

© Stack Overflow or respective owner

Related posts about c++

Related posts about if-statement