2

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
  • 3
    You don't have any assignment statements at all. Commented Aug 10, 2012 at 15:01

5 Answers 5

11

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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(); 

Comments

3

A mutiple assignement would looks like:

int num, size; num = size = query.constraints.size(); 

But the comma operator does not do a multiple assignement.

Comments

2

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.

Comments

0

The comma operator doesnt do what you think it does

4 Comments

then what is it? It can even be overloaded java2s.com/Tutorial/Cpp/0200__Operator-Overloading/…
It's just a separator in a list. Just like there's no comma operator in printf("Hello %s", world).
@Gir The comma operator can be overloaded. The comma in his statement isn't a comma operator, but part of syntax, and overloading the comma operator has no effect here.
because is a part of the variable declaration?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.