Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Multiple assignments to same variable in one line

I came across this code line in C:

#define RUNDE(n) ( K ^= Q[n], y = K, K = F(K) ^ xR, xR = y )

Is it valid to assign something to K multiple times? I thought it's invalid to change a variable more than one time in one statement.

like image 281
ElkeAusBerlin Avatar asked Jun 07 '26 18:06

ElkeAusBerlin


1 Answers

Is it valid to assign something to K multiple times?

That's perfectly valid C macro. A comma operator , is used here.

Using , operator you can assign a value to a variable multiple times.

e.g.K = 20, K = 30; This will assign 30 to K overwriting the previous value of 20.


I thought it's invalid to change a variable more than one time in one statement.

Yes it leads to undefined behavior if we try to modify a variable more than once in a same C statement but here first , is a sequence point.

So it's guaranteed that we will be modifying the K second time (K = 30) only when all the side effects of first assignment (K = 20) have taken place.

like image 125
rootkea Avatar answered Jun 10 '26 06:06

rootkea