3

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.

JBentley
  • 6,099
  • 5
  • 37
  • 72
user5574376
  • 371
  • 1
  • 5
  • 12

4 Answers4

9

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
3

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.

Claudiu
  • 224,032
  • 165
  • 485
  • 680
  • 2
    Declaring a variable isn't a statement. It is a *decl-statement,* and it isn't legal in other cognate contexts such as a single statement controlled by an if/while. – user207421 Jan 11 '16 at 09:25
  • 1
    @EJP What do you mean? In C++ it is legal to write `if (cond) int x = 0;`, even though this is pointless. – cpplearner Jan 12 '16 at 02:37
1

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.

Petr Stepanov
  • 71
  • 2
  • 9
0

For the above code, you can try this for c++

string finalgrade = []() {
        int grade = 100;
        return (grade < 60) ? "fail": "pass";
    }();