用逗号,而不是C和C分号的影响++ [英] Effect of using a comma instead of a semi-colon in C and C++

查看:166
本文介绍了用逗号,而不是C和C分号的影响++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重构一个逗号而不是用分号来单独声明各个部分C和C ++ code时,我注意到在许多场合。事情是这样的;

I've noticed on a number of occasions when refactoring various pieces of C and C++ code that a comma is used rather than a semi-colon to seperate statements. Something like this;

int a = 0, b = 0;
a = 5, b = 5;

在哪里我本来期望

Where I would have expected

int a = 0, b = 0;
a = 5; b = 5;

我知道,C和C ++允许使用逗号来单独报表(尤其是环头),但有什么区别,如果任何这两个code件之间?我的猜测是逗号一直留在剪切和放大器的结果;粘贴,但它是一个bug,它影响执行?

I know that C and C++ allow use of commas to seperate statements (notably loop headers), but what is the difference if any between these two pieces of code? My guess is that the comma has been left in as the result of cut & pasting, but is it a bug and does it effect execution?

推荐答案

它没有在code你贴的差异。一般情况下,逗号然而,分离前pressions就像一个分号,如果你把整个作为一个前pression,那么逗号操作符意味着前pression计算结果为最后一个参数。

It doesn't make a difference in the code you posted. In general, the comma separates expressions just like a semicolon, however, if you take the whole as an expression, then the comma operator means that the expression evaluates to the last argument.

下面是一个例子:

b = (3,5);

将评估3,然后是5和分配后到B。因此B = = 5。请注意,括号内是很重要的位置:

Will evaluate 3, then 5 and assign the latter to b. So b==5. Note that the brackets are important here:

b = 3, 5;

可否评价B = 3,则图5和整个前pression的结果为5,然而b == 3

Will evaluate b=3, then 5 and the result of the whole expression is 5, nevertheless b == 3.

逗号操作符是在for循环非常有用,当你的迭代code不是一个简单的我+ +,但你需要做多个命令。在这种情况下,分号不与for循环句法很好地起作用。

The comma operator is especially helpful in for-loops when your iterator code is not a simple i++, but you need to do multiple commands. In that case a semicolon doesn't work well with the for-loop syntax.

这篇关于用逗号,而不是C和C分号的影响++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆