Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ basic integer confusion [duplicate]

Tags:

c++

variables

I simply have the line as follows:

   int player = 1, i, choice;

My question is, what is assigned to i and what is assigned to choice? I was always taught that a variable could not be assigned to multiple values.

like image 354
I Hate School Avatar asked Feb 04 '26 17:02

I Hate School


2 Answers

That code is equivalent to saying

int player = 1;
int i;
int choice;

You are not assigning 1, i, and choice into the integer variable player.

like image 185
Chris Stauffer Avatar answered Feb 06 '26 07:02

Chris Stauffer


Nothing is assigned anywhere in this -- it's doing initialization not assignment.

player is obviously initialized to 1.

If this definition is at namespace scope so i and choice have static storage duration, then they will be zero-initialized.

If this definition is local to a function, i and choice will be default-initialized, which (in the case of int) means they aren't given a predictable value.

If this definition is inside a class, then i and choice can be initialized by a constructor. A constructor generated by the compiler will default-initialize them.

like image 27
Jerry Coffin Avatar answered Feb 06 '26 07:02

Jerry Coffin