序列点&&&运算符
Sequence point && operator
本文关键字:运算符 更新时间:2023-10-16
对于 c 03 ,标准称,&&操作员有一个序列点,因此在访问右操作员之前已经发生了左操作员的所有副作用。
so
int i = 0;
if (++i && i--)
std::cout << i;
定义很好,可以保证输出0
。
但是,这个问题是什么:正确操作数仅当左操作数不是 0
时评估吗?这似乎是一个细节,但是对我而言,标准仅保证操作数之间的序列点, 从未对左一个依赖性进行评估/访问。
,例如
int arr[10];
int pos; // somehow set to a value from 0 to 10
while (pos < 10 && arr[pos] != 0)
pos++;
这是定义的吗?pos
可以是从10
上开始的,也可以到达10
。左操作数具有 no 副作用,与右操作数同意。我保证arr[10] != 0
从未执行过吗?
编辑:
多亏了评论和答案,现在很明显:
5.14p2: "The result is a bool. If the second expression is evaluated,
every value computation and side effect associated with the first expression
is sequenced before every value computation and side effect associated with
the second expression."
是序列点的含义。
5.14p1: "Unlike &, && guarantees left-to-right evaluation: the second operand is
not evaluated if the first operand is false."
是短路的含义。
第一个没有第二个会使我的示例不确定。谢谢。
标准确实保证了&&
和||
的短路。
如果&&
的左侧是false
,则未评估右侧。对于||
,如果左侧为true
。
c 11的5.14p1,最后一句话:
与&amp;,&amp; amp;不同担保从左到右评估:如果第一操作数为false,则未评估第二操作数。
是的,可以保证。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 如何防止clang格式在流运算符调用之间添加换行符<<