F. Picazo F. Picazo - 1 month ago 5
C Question

Assigning to two pointers at the same time in C

I have a small segment of C code that I am a bit confused about.

int *p, *q, arr[4]={5,8,3,7}
p = q = arr;


Does the pointer assignment mean both
p
and
q
equal
arr
? Or that
p
equals
q
which equals
arr
? This has been bugging me for a while, any help appreciated

Answer

The assignment operator (=) is right associative. This means

a = b = c;

parses as

a = (b = c);

That is, the value of c is assigned to b, and the result value of this assignment operation is assigned to a.

The = operator is defined to return the value that was assigned, so this effectively sets both a and b to c.