Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

int

cin

Can the following two lines be condensed into one?

int foo;
std::cin >> foo;
like image 770
ayane_m Avatar asked Feb 16 '13 20:02

ayane_m


People also ask

Can variables be declared and initialized at the same time?

Variables can either be initialized in the same statement as the declaration or later in the code.

Can you initialize multiple variables in one line in C?

Example - Declaring multiple variables in a statementIf your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.

What is the correct syntax of initializing and declaring two variables that have the same value of 20?

int a = 20; int b; The variable a is initialized with a value in the program while the variable b is initialized dynamically.


2 Answers

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;
like image 67
Joseph Mansfield Avatar answered Oct 31 '22 20:10

Joseph Mansfield


You can... with

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

but you really should not do this

like image 24
6502 Avatar answered Oct 31 '22 19:10

6502