c++initializationdeclare

Is it possible to declare in the same expression, the variable that is going to be used by the expression?


I am studying declaration, definition and initialization in C++.
I built this proof of concept and I didn't understand compiler's error meaning.

The source code snippet:

#include <iostream>

int main ()
{
        std::cin >> int input_value;
        return 0;
}

When attempting to compile:

 % g++ -Wall -o p44e1 p44e1.cc
p44e1.cc:5:18: error: expected '(' for function-style cast or type construction
        std::cin >> int input_value;
                    ~~~ ^
1 error generated.

Solution

  • A function body consists of zero or more statements.

    There are several kinds of statements. We only care about two here:

    So std::cin >> int input_value; is outright invalid. int input_value; must be a separate statement, but you tried to embed it into an other (expression) statement.