3

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
ElkeAusBerlin
  • 565
  • 1
  • 4
  • 18
  • 6
    C or C++. PIck one. – NathanOliver Jan 14 '16 at 12:49
  • 1
    you might want to read up on [sequence points vs. undefined behavior](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) – Sander De Dycker Jan 14 '16 at 12:51
  • The comma operator is a sequence point, but indeed, your link is worth a read anyhow. – Bathsheba Jan 14 '16 at 12:51
  • @Bathsheba : I can see how the phrasing of my comment made it seem like I thought it was undefined behavior (which is not the case). But what I wanted to point out, is how undefined behavior is linked to the sequence points, not to statements like the OP thought. – Sander De Dycker Jan 14 '16 at 12:57

4 Answers4

4

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.

rootkea
  • 1,474
  • 2
  • 12
  • 32
2

This is well-defined as the comma operator evaluates its first operand before its second.

However, IMHO this code is horrible and you shouldn't write it. inline functions exist to do things like this; using the preprocessor is just abuse. Sure, you would need to pass some arguments to an inline function, but this is far preferable to relying on names from the surrounding scope.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
1

In C++ this would be regarded as nasty; in C it's permissible as the reliance on the preprocessor is more necessary.

But in either case your expression is perfectly well-defined. The comma operator (which is evaluated from left to right), acts as a sequenced expression separator.

The elegant thing with this macro is that its value is the value of xR = y, which is the final value of y.

But the inelegance of this macro, such as using variable names that are not passed as arguments, probably outweighs any benefits. My inclination is to bin it.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

It is a valid comma operator, that perform all statements in sequence, returning the value of the last statement.

That macro is a sequence of assignments, using the last assignment (y or xR) as return value