Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaration can not happen inside a conditional operator expression?

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.

like image 670
user5574376 Avatar asked Jul 21 '26 05:07

user5574376


2 Answers

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.

like image 178
Kerrek SB Avatar answered Jul 22 '26 22:07

Kerrek SB


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.

like image 21
Claudiu Avatar answered Jul 22 '26 21:07

Claudiu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!