条件语句中逗号的优点是什么? [英] What is the advantage of commas in a conditional statement?

查看:316
本文介绍了条件语句中逗号的优点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以写一个 if 语句为

if (a == 5, b == 6, ... , thisMustBeTrue)

并且只有最后一个条件应该输入 if 正文是否可以满足。

and only the last condition should be satisfiable to enter the if body.

为什么允许这样做?

推荐答案

稍微改变你的例子,假设是这个

Changing your example slightly, suppose it was this

if ( a = f(5), b = f(6), ... , thisMustBeTrue(a, b) )

(注意 = 而不是 == )。在这种情况下,逗号保证从左到右的评估顺序。相比之下,这个

(note the = instead of ==). In this case the commas guarantee a left to right order of evaluation. In constrast, with this

if ( thisMustBeTrue(f(5), f(6)) )

你不知道之前是否调用 f(5)或在 f(6)之后。

you don't know if f(5) is called before or after f(6).

更正式地说,逗号允许你写一个序列表达式(a,b,c),就像使用; 编写一系列语句一样 A; b; ℃;
就像; 创建一个序列点(完整表达式结束)逗号也是如此。只有序列点控制评估顺序,请参阅此帖子

More formally, commas allow you to write a sequence of expressions (a,b,c) in the same way you can use ; to write a sequence of statements a; b; c;. And just as a ; creates a sequence point (end of full expression) so too does a comma. Only sequence points govern the order of evaluation, see this post.

但当然,在这种情况下,你实际上写的是

But of course, in this case, you'd actually write this

a = f(5);
b = f(6);    
if ( thisMustBeTrue(a, b) )

所以什么时候以逗号分隔的顺序表达式优先于; 分隔的语句序列?几乎从来没有我会说。当你希望右侧替换为单个表达时,也许在宏中。

So when is a comma separated sequence of expressions preferrable to a ; separated sequence of statements? Almost never I would say. Perhaps in a macro when you want the right-hand side replacement to be a single expression.

这篇关于条件语句中逗号的优点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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