Search code examples
ccomma-operator

Unclear behavior of "," operator in C


In a given code I found following sequence,

data = POC_P_Status, TE_OK;

I don't understand what that does mean.

Does the data element receive the first or the second element or something else?

Update:

I read somewhere that this behavior is like this,

if i would write that:

if(data = POC_P_Status, TE_OK) { ... }

then teh if clause will be true if TE_OK is true.

What do you mean?


Solution

  • It's equivalent to the following code:

    data = POC_P_Status;
    TE_OK;
    

    In other words, it assigns POC_P_Status to data and evaluates to TE_OK. In your first case, the expression stands alone, so TE_OK is meaningful only if it's a macro with side effects. In the second case, the expression is actually part of an if statement, so it always evaluates to the value of TE_OK. The statement could be rewritten as:

    data = POC_P_Status;
    if (TE_OK) { ... }
    

    From the C11 draft (http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf) :

    The left operand of a comma operator is evaluated as a void expression; there is a sequence point after its evaluation. Then the right operand is evaluated; the result has its type and value. If an attempt is made to modify the result of a comma operator or to access it after the next sequence point, the behavior is undefined.

    That means that in the expression:

    a, b
    

    The a is evaluated and thrown away, and then b is evaluated. The value of the whole expression is equal to b:

    (a, b) == b
    

    Comma operator is often used in places where multiple assignments are necessary but only one expression is allowed, such as for loops:

    for (int i=0, z=length; i < z; i++, z--) {
        // do things
    }
    

    Comma in other contexts, such as function calls and declarations, is not a comma operator:

    int func(int a, int b) {...}
                  ^
                  |
                  Not a comma operator
    
    int a, b;
         ^
         |
         Not a comma operator