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.
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.
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
.
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.
They (i
and choice
) have unspecified values. They can be pretty much any value, really. Unless you explicitly set them to a value, they are given some "junk" value (typically whatever is already in that memory location that they've been assigned).
You're not assigning to player
multiple times. You're creating 3 variables, and assigned 1
to player
. It's the same as if you had written:
int player = 1;
int i;
int choice;
Think of this as:
int player = 1;
int i;
int choice;
In c++ you are allowed to declare multiple of the same data type on the same line, like
char c1, c2, c3;
and it is also accepted to give one of these a value in their declaration, like what your line is doing. So as simonc said, there will be no value in i or choice.
What you have there is definition & initialization, definition, definition;
int player = 1;
int i;// = most probably 'random' trash from heap/stack memory
int choice;// = most probably 'random' trash from heap/stack memory
i and choice aren't defined. What happens is, you are saying: I want to declare player as int and asign 1 to it then a sequens interupt sign(,), says the type specifier has reference to the next sequenz. Means also to declare i and choice as int (but without asigning anythign)