开发者

comma operator and comma seperator in c++ [duplicate]

This question already has answers here: Closed 11 years ago.

P开发者_高级运维ossible Duplicate:

When all does comma operator not act as a comma operator?

when does comma(,) behave as operator and when does it behave as separator?And what are the consequences of it.If possible please give small examples too for both.


The comma behaves as a separator in function calls, function declarations, initializers and variable declarations:

f(a, b);
int a[] = {2, 3, 4};
int c = 2, d = 3;

By contrast, when used to separate statements, it behaves as the comma operator:

a = 2, b = 3;
c = (doSomething(), doSomethingElse(), result());

The result it yields is the value of its rightmost operand and the order of execution is guaranteed to be left to right, contrary to the undefined order of evaluation of function arguments.


Comma as Operator

The comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, it 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.

Example:

/int i = (5, 10);  /* 10 is assigned to i*/

The primary use of the comma operator is to produce side effects in the following situations:

  • Calling a function.
  • Entering or repeating an iteration loop.
  • Testing a condition.
  • Other situations where a side effect is required but the result of the expression is not immediately needed.

Comma as Separator

Comma acts as a separator when used with function calls and definitions, function like macros, variable declarations, enum declarations, and similar constructs.

Example:

int a = 1, 
b = 2; 
void fun(x, y);

Another Example:

void fun(f1(), f2()); 


Basically, it behaves as an operator everywhere that an expression is required (as opposed to a list of expressions).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜