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.