Thursday, April 12, 2012

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

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?





1 comment:

  1. 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.

    ReplyDelete