逗号运算符通常用来分隔变量说明、函数参数、表达式以及for语句中的元素。
下例给出了使用逗号的多种方式:
#include <stdio.h>
#include <stdlib.h>
void main ()
{
/* Here, the comma operator is used to separate
three variable declarations. */
int i, j, k;
/* Notice how you can use the comma operator to perform
multiple initializations on the same line. */
i=0, j=1, k=2;
printf("i= %d, j=%d, k= %d\n", i, j, k);
/* Here, the comma operator is used to execute three expressions
in one line: assign k to i, increment j, and increment k.
The value that i receives is always the rigbtmost expression. */
i= ( j++, k++ );
printf("i=%d, j=%d, k=%d\n", i, j, k);
/* Here, the while statement uses the comma operator to
assign the value of i as well as test it. */
while (i=(rand() % 100), i !=50)
printf("i is %d, trying again... \n", i)
printf ("\nGuess what? i is 50!\n" )
}
请注意下述语句:
i:(j++,k++)
这条语句一次完成了三个动作,依次为:
此外,还要注意看上去有点奇怪的while语句:
while (i=(rand() % 100), i !=50)
printf("i is %d, trying again... \n");
这里,逗号运算符将两个表达式隔开,while语句的每次循环都将计算这两个表达式的值。逗号左边是第一个表达式,它把0至99之间的一个随机数赋给i;第二个表达式在while语句中更常见,它是一个条件表达式,用来判断i是否不等于50。while语句每一次循环都要赋予i一个新的随机数,并且检查其值是否不等于50。最后,i将被随机地赋值为50,而while语句也将结束循环。
请参见:
1、运算符的优先级总能保证是“自左至右”或“自右至左”的顺序吗?
2、++var和var++有什么区别?