Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable assignment inside a C++ 'if' statement

In C++, the following is valid and I can run it without a problem:

int main(){
    if (int i=5)
        std::cout << i << std::endl;
    return 0;
}

However, even though the following should also be valid, it gives me an error:

if ((int i=5) == 5)
    std::cout << i << std::endl;

Error:

test.cpp: In function ‘int main()’:
test.cpp:4:10: error: expected primary-expression before ‘int’
     if ((int i=5) == 5)
          ^
test.cpp:4:10: error: expected ‘)’ before ‘int’
test.cpp:5:36: error: expected ‘)’ before ‘;’ token
         std::cout << i << std::endl;
                                        ^

Furthermore, in C++17 the below code must be valid too, but it gives me a similar error again:

if (int i=5; i == 5)
    std::cout << i << std::endl;

Error:

test.cpp: In function ‘int main()’:
test.cpp:4:16: error: expected ‘)’ before ‘;’ token
     if (int i=5; i == 5)
                ^
test.cpp:4:18: error: ‘i’ was not declared in this scope
     if (int i=5; i == 5)
                  ^

I am trying to compile with g++ test.cpp -std=c++17. g++ --version gives me g++ (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609. What am I missing here?

like image 276
Teshan Shanuka J Avatar asked Nov 23 '25 14:11

Teshan Shanuka J


2 Answers

if ((int i=5) == 5) is a syntax error. It does not match any supported syntax for if statements. The syntax is init-statement(optional) condition, where condition could either be an expression, or a declaration with initializer. You can read more detail about the syntax on cppreference.

if (int i=5; i == 5) is correct. However, you are using an old version of GCC that dates from before C++17 was standardized. You would need to upgrade your compiler version. According to C++ Standards Support in GCC this feature was added in GCC 7.

like image 170
M.M Avatar answered Nov 25 '25 04:11

M.M


For starters, I believe your compiler is right to reject

if ((int i=5) == 5)

because this is not legal C++ code. A variable declaration statement isn’t an expression, so you can’t treat (int i = 5) as an expression.

For the second one, I suspect you just need to update your compiler. g++ 5.6 is a fairly old version at this point, and I believe more updates versions of g++ will handle that code with no problem.

like image 30
templatetypedef Avatar answered Nov 25 '25 04:11

templatetypedef