Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 482
Angus Comber Avatar asked Dec 21 '22 23:12

Angus Comber


1 Answers

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.

like image 172
Luchian Grigore Avatar answered Dec 24 '22 01:12

Luchian Grigore