Should the if((int val = getvalue()) == x) form work

c++

Solution

It's not legal because you can't use a statement as an expression.

So, it's not the declaring a variable inside an `if` that's illegal, but the comparison.

Just like:

(int x = 3) == 3;

is illegal, whereas

int x = 3;
x == 3;

isn't.

Problem

This form does not compile with my VS2008 compiler. Should it be possible? ``` #include <iostream> using namespace std; int getvalue() { return 3; } int main(int argc, char* argv[]) { if((int val = getvalue()) == 3) cout << "val=" << val << "\n"; return 0; } ``` This form does work. ... ``` int val; if((val = getvalue()) == 3) ... ``` Why does it not work?

Original source