问题
I have multiple assignment statement in my program as shown below where query.constraints.size()
is supposed to return 13
(constraints
is an array and its returning its size)
int num,size = query.constraints.size();
When I do this size
becomes 13 as expected but num
becomes 9790272 for some reason.
When I do them separately as below everything is ok and both of them are 13 as expected
int size = query.constraints.size();
int num = query.constraints.size();
Why does my multiple assignment result in a strange a strange value ?
回答1:
Why does my multiple assignment result in a strange a strange value ?
Because C++ has no multiple assignment1. You are declaring two variables here, but only initialise the second, not the first.
1 Well, you can do int a, b = a = c;
but code which does this would be deemed bad by most C++ programmers except in very peculiar circumstances.
回答2:
You're not assigning multiple times, you're declaring multiple times. You need to do something like:
int num, size;
size = num = query.constraints.size();
回答3:
What you have is actually a declaration statement, partially with initializer. Your code is equivalent to this code:
int num; // uninitialized, you're not allowed to read it
int size(query.constraints.size()); // initialized
In general, T x = expr;
declares a variable x
of type T
and copy-initializes it with the value of expr
. For fundamental types this just does what you expect. For class-types, the copy-constructor is only formally required, but in practice usually elided.
回答4:
A mutiple assignement would looks like:
int num, size;
num = size = query.constraints.size();
But the comma operator does not do a multiple assignement.
回答5:
The comma operator doesnt do what you think it does
来源:https://stackoverflow.com/questions/11904307/strange-multiple-assignment-error-in-c