dimanche 15 mars 2020

Variable assignment inside 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 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?

Aucun commentaire:

Enregistrer un commentaire