Can a variable be initialized with an istream on the same line it is declared?

ayane_m picture ayane_m · Feb 16, 2013 · Viewed 7.7k times · Source

Can the following two lines be condensed into one?

int foo;
std::cin >> foo;

Answer

Joseph Mansfield picture Joseph Mansfield · Feb 16, 2013

The smart-ass answer:

int old; std::cin >> old;

The horrible answer:

int old, dummy = (std::cin >> old, 0);

The proper answer: old has to be defined with a declaration before it can be passed to operator>> as an argument. The only way to get a function call within the declaration of a variable is to place it in the initialization expression as above. The accepted way to declare a variable and read input into it is as you have written:

int old;
std::cin >> old;