Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a comma separated set of assignments?

Tags:

c

I noticed in a routine

else 
  *pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);

Why does it work?

What does it do?

like image 525
j riv Avatar asked Dec 04 '10 09:12

j riv


Video Answer


2 Answers

From Wikipedia:

In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type). The comma operator has the lowest precedence of any C operator, and acts as a sequence point.

The use of the comma token as an operator is distinct from its use in function calls and definitions, variable declarations, enum declarations, and similar constructs, where it acts as a separator.

In this example, the differing behavior between the second and third lines is due to the comma operator having lower precedence than assignment.

int a=1, b=2, c=3, i;   // comma acts as separator in this line, not as an operator
i = (a, b);             // stores b into i                                ... a=1, b=2, c=3, i=2
i = a, b;               // stores a into i. Equivalent to (i = a), b;     ... a=1, b=2, c=3, i=1
i = (a += 2, a + b);    // increases a by 2, then stores a+b = 3+2 into i ... a=3, b=2, c=3, i=5
i = a += 2, a + b;      // increases a by 2, then stores a = 5 into i     ... a=5, b=2, c=3, i=5
i = a, b, c;            // stores a into i                                ... a=5, b=2, c=3, i=5
i = (a, b, c);          // stores c into i                                ... a=5, b=2, c=3, i=3

Link: http://en.wikipedia.org/wiki/Comma_operator

like image 127
Jesus Oliva Avatar answered Nov 02 '22 19:11

Jesus Oliva


A comma operator is a sequence point : each comma separated expression are evaluated from left to right. The result has the type and value of the right operand. Functionally, your example is equivalent to (the much more readable ?) :

else
{
    *pbuf++ = '%';
    *pbuf++ = to_hex(*pstr >> 4);
    *pbuf++ = to_hex(*pstr & 15);
}

Here is another example that the standard provides for the comma operator (6.5.17) :

In the function call

f(a, (t=3, t+2), c)

the function has three arguments, the second of which has the value 5.

like image 27
icecrime Avatar answered Nov 02 '22 18:11

icecrime