开发者

What is a comma separated set of assignments?

I noticed in 开发者_Go百科a routine

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

Why does it work?

What does it do?


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.


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


Why it shouldn't work? It sets %, to_hex(*pstr >> 4), to_hex(*pstr & 15) to sequential memory block addressed by pbuf. The equivalent code may be the following:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜