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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With