使用赋值作为条件表达式? [英] Using assignment as a condition expression?

查看:277
本文介绍了使用赋值作为条件表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑:

if (a=5) {
   /* do something */
}

作业如何作为条件工作?

How does the assignment work as a condition?

是否基于l值的非零值?

Is it based on non-zero value of l-value?

推荐答案

C ++— ISO / IEC 14882:2003(E)



C++ — ISO/IEC 14882:2003(E)


[5.17 / 1] 是几个赋值运算符,所有这些都从右到左分组
。所有都需要可修改的左值作为它们的左操作数
,并且赋值表达式的类型是其左操作数的类型。
赋值操作的结果是赋值之后存储在左
操作数中的值
; a = 5 结果是一个左值。

[5.17/1] There are several assignment operators, all of which group right-to-left. All require a modifiable lvalue as their left operand, and the type of an assignment expression is that of its left operand. The result of the assignment operation is the value stored in the left operand after the assignment has taken place; the result is an lvalue.



<是 5


[6.4 / 4] / code> [..]作为表达式的条件的值是
表达式的值,隐式转换为 bool 用于
开关以外的语句。 [..]

[6.4/4] [..] The value of a condition that is an expression is the value of the expression, implicitly converted to bool for statements other than switch. [..]

发生到 bool 的转换。


[4.12 / 1] 算术,枚举,指针或指向成员的右值
类型可以转换为 bool 类型的右值。零值,null
指针值或空成员指针值转换为 false ; 任何
其他值转换为 true

[4.12/1] An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.

5 转换为布尔值 true

[6.4.1 / 1] 如果条件(6.4)产生true,则执行第一个
子语句。
[..]

true code> if 语句成功。

true is treated as an if statement success.


[6.5.16 / 3] 赋值运算符将值存储在由左操作数指定的对象
中。 赋值表达式在赋值后具有左操作数的值
,但不是一个左值。 [..]

[6.5.16/3] An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment, but is not an lvalue. [..]

表达式 a = 5 的结果为 5


[6.8.4.1/2] / code>在两种形式中,如果
表达式比较不等于0
,则执行第一个子语句。 [..]

[6.8.4.1/2] In both forms, the first substatement is executed if the expression compares unequal to 0. [..]

5 被视为 if 语句成功。

这样的代码几乎总是一个错误;作者可能希望 if(a == 5){} 。然而,有时是故意的。您可能会看到如下代码:

Code like this is almost always a mistake; the author likely intended if (a == 5) {}. However, sometimes it is deliberate. You may see code like this:

if (x = foo()) {
   cout << "I set x to the result of foo(), which is truthy";
   // ... stuff
}

这篇关于使用赋值作为条件表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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