I wonder why I can not declare a variable inside the following expression.
string finalgrade = ( ( int grade = 100 ) < 60 ) ? "fail" : "pass";
While we can declare a variable inside a for statement.
I wonder why I can not declare a variable inside the following expression.
string finalgrade = ( ( int grade = 100 ) < 60 ) ? "fail" : "pass";
While we can declare a variable inside a for statement.
In C++, declarations are only allowed within a declaration statement and within the control structures if
, while
and for
.
Since the purpose of a declaration is to introduce a name, a declaration only makes sense when there is a containing scope in which the name is visible, and that makes those options the only sensible ones. Declaration statements introduce the name into the surrounding scope, and the three control structures each contain their own, inner scopes into which the respective declarations introduce the name.
It's just a matter of how the syntax of C++ is defined. You can't put statements in expressions and declaring a variable is a decl-statement. A for loop takes a decl-statement as its initializer, so a variable can be declared there.
You could theoretically have a syntax where the code you wrote would work. But it would probably be fairy confusing. What's the scope of the declared variable? And programmers would be required to look deep into expressions to see whether a variable wasn't secretly declared somewhere.
I think it may correspond to the fact that in C++ specs the declaration/initialization statement like int var = val
is a piece of code that is basically equivalent to two others: int var
which is statement and var = 5
which is expression and gives a chunk of memory to a variable with the assigned value. So, basically what you are trying to do is to compare statement that has no return value with a number.
To illustrate it better try to run the following code:
int main(){
int i;
if ((i = 100) > 60){
std::cout << "It worked!";
}
return 0;
}
You will see that this code compiles since now you compare expression i = 100
that returns value and a number.
For the above code, you can try this for c++
string finalgrade = []() {
int grade = 100;
return (grade < 60) ? "fail": "pass";
}();