在C和C++中,逗号(,)可以在两个上下文中使用: 1) 逗号作为运算符: 逗号运算符(由标记表示)是一个二进制运算符,它计算第一个操作数并丢弃结果,然后计算第二个操作数并返回此值(和类型)。逗号运算符在所有C运算符中具有最低的优先级,并充当 序列点 .
C
/* comma as an operator */ int i = (5, 10); /* 10 is assigned to i*/ int j = (f1(), f2()); /* f1() is called (evaluated) first followed by f2(). The returned value of f2() is assigned to j */ |
2) 逗号作为分隔符: 当与函数调用和定义、函数类宏、变量声明、枚举声明和类似构造一起使用时,逗号充当分隔符。
C
/* comma as a separator */ int a = 1, b = 2; void fun(x, y); |
逗号作为分隔符的使用不应与运算符的使用相混淆。例如,在下面的语句中,可以按任意顺序调用f1()和f2()。
C
/* Comma acts as a separator here and doesn't enforce any sequence. Therefore, either f1() or f2() can be called first */ void fun(f1(), f2()); |
看见 这 对于C vs VC++使用逗号算符的差异。 你可以尝试下面的程序来检查你对C中逗号的理解。
C
// PROGRAM 1 #include <stdio.h> int main() { int x = 10; int y = 15; printf ( "%d" , (x, y)); getchar (); return 0; } |
C
// PROGRAM 2: Thanks to Shekhu for suggesting this program #include <stdio.h> int main() { int x = 10; int y = (x++, ++x); printf ( "%d" , y); getchar (); return 0; } |
C
// PROGRAM 3: Thanks to Venki for suggesting this program #include <stdio.h> int main() { int x = 10, y; // The following is equivalent // to y = x + 2 and x += 3, // with two printings y = (x++, printf ( "x = %d" , x), ++x, printf ( "x = %d" , x), x++); // Note that last expression is evaluated // but side effect is not updated to y printf ( "y = %d" , y); printf ( "x = %d" , x); return 0; } |
代码中的以下表达式:
a=2,3,4;
评估结果如下:
(a=2,3,4);
这是因为赋值运算符的优先级高于逗号运算符。
C++
#include <iostream> using namespace std; int main() { int a = 5; a = 2, 3, 4; cout << a; return 0; } |
3) 逗号运算符代替分号。 我们知道在C和C++中,每个语句都用分号终止,但是逗号运算符也用于在满足下列规则后终止语句。
- 变量声明语句必须以分号结尾。
- 声明语句后的语句可以用逗号运算符终止。
- 程序的最后一条语句必须以分号结尾。
例如:
CPP
#include <iostream> using namespace std; int main() { cout << "First Line" , cout << "Second Line" , cout << "Third Line" , cout << "Last line" ; return 0; } |
输出:
First LineSecond LineThird LineLast line
尽量不要混淆逗号作为分隔符和逗号作为运算符。示例:
int a=4,3;
这将生成一个错误,因为在本例中,逗号在声明发生时充当分隔符。因此,无错误代码如下所示:
INTA;
a=4,3;
现在a中存储的值将是4。
此外,以下内容有效:,
int a=(4,3);
这里,3存储在a中。
参考资料: http://en.wikipedia.org/wiki/Comma_operator http://publib.boulder.ibm.com/infocenter/comphelp/v101v121/index.jsp?topic=/com.ibm.xlcpp101.aix.doc/language_ref/co.html http://msdn.microsoft.com/en-us/library/zs06xbxh.aspx 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。