Studying initialization in C++: what does "error: expected '(' for function-style cast or type construction" means in this case?


I am studying initialization in C++. In this proof of concept. I don’t understand compiler’s advice.
(I already know that declaring a variable inside a cin is not the easy and natural (not even perhaps legal or even apropiate) way. Would be easy to just declare it outside before and no problem. But i asked the question just to understand more deeply what is going on. Trying to understand C++ in a better way and initialization in particular, which is known not to be a trivial subject).

#include <iostream>

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

when trying to compile:

 % g++ -Wall -o p44e1 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 several kinds of statements. We only care about two here:

  • A declaration statement, e.g. int input_value;

  • An expression statement. That is, e;. Where e is an expression, meaning "operands connected with operators, or individual operands".

    std::cin >> input_value; would be an expression statement, where std::cin >> input_value is an expression (std::cin and input_value are operands, and >> is an operator).

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.

Leave a ReplyCancel reply