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

倖福魔咒の 提交于 2019-12-23 18:33:08

问题


Possible 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.


回答1:


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.




回答2:


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()); 



回答3:


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



来源:https://stackoverflow.com/questions/6502819/comma-operator-and-comma-seperator-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!