前段时间,某童鞋碰到一个和逗号运算符相关的诡异问题,当时我也查了下运算符优先级,仔细想了半天才想明白,当时就想把关于逗号运算符的一些东西写一下,但由于比较忙,一直没写,现在补上。
在这里,为了省事,直接把邮件内容附上(假如那位童鞋你看到了,侵犯了你的版权,别生气哈~),我承认我真的很懒。。。
===============================================
对了能解释下这个问题么?
void main ()
{
bool test=false;
int a = 1;
test == true ? printf("hello\ "), printf("world\
"),a++ :
printf("Ha\ "), a++, a++;
printf("%d", a);
}
Test = false 的时候 a = 3;
Test = true 的时候 a = 4;
void main ()
{
bool test=false;
int a = 1;
test == true ? printf("hello\ "), printf("world\
"),a++ :
(printf("Ha\ "), a++, a++);
printf("%d", a);
}
Test = false 的时候 a = 3;
Test = true 的时候 a =1;
最近写程序的时候发现的貌似逗号和问号表达式连用的时候有些奇怪
==================================
在C语言中,逗号运算符优先级是最低的,所以第一个表达式等于:
(test == true ? printf("hello\ "), printf("world\
"),a++ :
printf("Ha\ ")), a++, a++;
所以:
Test = false 的时候 a = 3;
Test = true 的时候 a = 4;
? :运算符一般很容易理解成:管的范围是到分号,而事实上,按优先级,只管到逗号。之后的是另外一个表达式
对于这些不太清楚的优先级,一般都加括号,反正括号优先级够高。
逗号运算符的作用就是将两个表达式连接起来,整个表达式的值,等于最后一个表达式的值。
比如,上面改为:
test = true;
b = (test == true ? printf("hello\ "), printf("world\
"),a++ :printf("Ha\ "), a++, a++);
printf("%d,%d", a,b);
则输出为 a=4,b=3
反之,如果去掉括号
test = true;
b = test == true ? printf("hello\ "), printf("world\
"),a++ :printf("Ha\ "), a++, a++;
printf("%d,%d", a,b);
则a=4,b=1(等号的优先级比逗号高,但比?:低)
如果上面的test=false,
test = false;
b = test == true ? printf("hello\ "), printf("world\
"),a++ :printf("Ha\ "), a++, a++;
printf("%d,%d", a,b);
则a=3,b=3
因为printf的返回值,打印成功的话,返回打印的char个数,否则,返回负数。
Comments (6)
好诡异的用法。。。为毛不直接用if。。。
@grapeot
不知道,其实直接括号括起来也行啊,反正我是这样的,不清楚的就加括号
太菜了 没明白。。。。
太误人子弟了,用GCC 运行一下 在说~
@wersfsf
GCC没跑过,但我用Dev C++跑过,结果如文中所述
貌似加括号情况下,当test为true时,打印的a的值为2