Search code examples
cdelphicomma-operator

C code (with comma operator) to Delphi


What is the equivalent Delphi code for the following in C:

int32 *P;
int32 c0, c1, i, t;
uint8 *X;

t = P[i], c0 = X[t], c1 = X[t + 1];

Frankly, the comma operator confuses me. Is the following wildly wrong?

{$POINTERMATH ON}
var P: ^Int32; c0, c1, i, t: Int32; X: ^UInt8;

t:= P[i];   //<--?
c0:= X[t];
c1:= X[t+1];
t:= c1;     //<--?

Solution

  • The comma operator in C has the lowest possible precedence. So your statement is equivalent to:

    (t = P[i]), (c0 = X[t]), (c1 = X[t + 1]);
    

    which is then evaluated from left to right. So it's equivalent to:

    t = P[i];
    c0 = X[t];
    c1 = X[t + 1];
    

    However, if you had done something like this:

    z = (a = b, c = d);
    

    then it would be equivalent to this:

    a = b;
    c = d;
    z = c;
    

    because the comma operator "returns" its final operand.

    I should also point out that because each comma is a sequence point, stuff like this is well-defined:

    i = i + 1, i++, --i;
    

    where as this isn't:

    i = i + i++ - --i;
    


    It almost goes without saying: if anyone wrote production C code like your first code snippet, I would have to spank them.