Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange multiple assignment error in C++

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 ?

like image 346
Cemre Mengü Avatar asked Nov 16 '25 20:11

Cemre Mengü


2 Answers

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.

like image 98
Konrad Rudolph Avatar answered Nov 19 '25 08:11

Konrad Rudolph


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();
like image 40
jli Avatar answered Nov 19 '25 09:11

jli