什么是正确使用逗号操作的? [英] What is the proper use of the comma operator?

查看:128
本文介绍了什么是正确使用逗号操作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到这个code:

 如果(条件){
    PERROR(发生错误),出口(1);
}

为什么要这么做?为什么不干脆:

 如果(条件){
    PERROR(发生错误);
    出口(1);
}


解决方案

在你的榜样,也是没有道理可言。当书面这是一次有益的。

 如果(条件)
  PERROR(发生错误),出口(1);

- 那么你不这样做的需要大括号内。但它是一个邀请灾难。

逗号操作符是将两个或更多个前pressions在一个位置,所述参考只允许一个。你的情况,也没有必要使用它;在其他情况下,如在一while循环中,它可能是有用的:

 同时(A = B,C< D​​)
  ...

其中,while循环的实际的评价完全是统治的最后一个前pression。

I saw this code:

if (cond) {
    perror("an error occurred"), exit(1);
}

Why would you do that? Why not just:

if (cond) {
    perror("an error occurred");
    exit(1);
}

解决方案

In your example it serves no reason at all. It is on occasion useful when written as

if(cond)
  perror("an error occured"), exit(1) ;

-- then you don't need curly braces. But it's an invitation to disaster.

The comma operator is to put two or more expressions in a position where the reference only allows one. In your case, there is no need to use it; in other cases, such as in a while loop, it may be useful:

while (a = b, c < d)
  ...

where the actual "evaluation" of the while loop is governed solely on the last expression.

这篇关于什么是正确使用逗号操作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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