C 和 C++ 中是否有一种方法可以使返回 void 的函数以未指定的顺序求值?
我知道函数参数以未指定的顺序求值,因此对于不返回 void 的函数,这可用于以未指定的顺序求值这些函数:
#include <stdio.h>
int hi(void) {
puts("hi");
return 0;
}
int bye(void) {
puts("bye");
return 0;
}
int moo(void) {
puts("moo");
return 0;
}
void dummy(int a, int b, int c) {}
int main(void) {
dummy(hi(), bye(), moo());
}
由符合规范的编译器编译的合法 C 和 C++ 代码可以按任何顺序打印 hi
、bye
和 moo
。这不是未定义的行为(鼻恶魔是无效的),只是不止一个但少于无限的有效输出,兼容的编译器甚至不需要确定性它产生什么。
如果没有虚拟返回值,有没有办法做到这一点?
说明:这是一个关于 C 和 C++ 的抽象问题。一个更好的原始措辞可能是在任何上下文中没有为返回 void 的函数指定函数评估顺序?我不是要解决特定问题。
最佳答案
您可以利用以下事实,即逗号运算符的左侧是一个废弃的值表达式(C 中的 void 表达式),如下所示 ( see it live ):
int main(void) {
dummy((hi(),0), (bye(),0), (moo(),0));
}
来自 C++ 标准草案 5.18
逗号运算符:
A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded-value expression (Clause 5).
和 C11 部分 6.5.17
逗号运算符:
The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.
正如 Matt 指出的那样,也可以将上述方法与算术运算符混合使用以实现未指定的评估顺序:
(hi(),0) + (bye(),0) + (moo(),0) ;
关于c++ - 函数返回 void 的无序函数评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27263729/