我对函数调用的顺序感到困惑。我列出了我尝试过的订单,但仍然得到错误的答案。
!!!答案是“i 和 j 值未定义。”
按照运算符优先级:
- if compiler calculates the values from left to right
int i = (1+0) || (ignored); //1
int j = (1) || (ignored); //1
- if compiler firstly calculates the value after '+', calculates other values from left to right
int i = (0+0) || (1); //1
int j = (2) || (ignored); //1
我仍然得出错误的结论。
所以我尝试违反运算符优先级
- if compiler first calculates the values from right to left
int i = (1+1) || (0); //1
int j = (ignored) || (2+2); //1
- if compiler only first calculates the value before '+', calculates other values from right to left
int i = (0+1) || (0); //1
int j = (ignored) || (1+2); //1
我仍然得出错误的结论。
我再次猜测编译器可能不会忽略 || 之后的表达式即使 left 为 true
- if compiler calculates the values from left to right
int i = (1+0) || (1); //1
int j = (2) || (2+3); //1
- if compiler firstly calculates the value after '+', calculates other values from left to right
int i = (0+0) || (1); //1
int j = (2) || (3+3); //1
- if compiler first calculates the values from right to left
int i = (1+1) || (0); //1
int j = (3) || (2+2); //1
- if compiler only first calculates the value before '+', calculates other values from right to left
int i = (0+1) || (0); //1
int j = (3) || (1+2); //1
我仍然得出错误的结论。
#include<stdio.h>
int x = 0;
int f(){
if(x == 0) return x + 1;
else return x - 1;
}
int g(){
return x++;
}
int main(){
int i = (f() + g()) || g();
int j = g() || (f() + g());
}
无论顺序如何,除了 i=1 且 j 值为 1 外,I 均为 1。
但答案是 i 和 j 值未定义。
我想知道哪种情况会导致另一个输出...
原谅我的愚蠢......
最佳答案
让我们分析一下i
。请注意,||
的第二个参数仅在左侧参数为 0 时计算。
i
始终为 1,即使获得此结果的方法未指定。
这里没有未定义的行为。 (从形式上来说,这是因为函数调用是一个顺序步骤。)
该语言没有指定在左侧求值时调用f()
和g()
的顺序。这留待实现。从形式上来说,它甚至不是由实现定义的,因为不需要实现来记录行为。如果首先调用 f()
,则 f() + g()
的值非零。如果首先调用g()
,则f() + g()
为零,因此再次调用g()
,即也非零,因为此时 x
为 1。
j
会被简单地丢弃为 1,因为仅评估 ||
的左侧。
一个更有趣的变体是
int f(){
if(x == 0) return ++x;
else return --x;
}
实际上不同的实现可能会为 i
或 j
返回 0 或 1。
关于c - 如何确定逻辑表达式中函数调用的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55573723/