c - 如何确定逻辑表达式中函数调用的顺序

标签 c

我对函数调用的顺序感到困惑。我列出了我尝试过的订单,但仍然得到错误的答案。

!!!答案是“i 和 j 值未定义。”

按照运算符优先级:

  1. if compiler calculates the values from left to right
   int i = (1+0) || (ignored);  //1  
   int j = (1) || (ignored);   //1 
  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 

我仍然得出错误的结论。

所以我尝试违反运算符优先级

  1. if compiler first calculates the values from right to left
   int i = (1+1) || (0);  //1
   int j = (ignored) || (2+2);  //1
  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

  1. if compiler calculates the values from left to right
   int i = (1+0) || (1);    //1
   int j = (2) || (2+3);    //1
  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
  1. if compiler first calculates the values from right to left
   int i = (1+1) || (0);  //1
   int j = (3) || (2+2);  //1
  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;
}

实际上不同的实现可能会为 ij 返回 0 或 1。

关于c - 如何确定逻辑表达式中函数调用的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55573723/

相关文章:

c++ - C/C++ 以十六进制打印字节,得到奇怪的十六进制值

c - C 编程中的指针和字符串

c - ls 与 nohup 配合不好

c - 在 C 的不同线程中运行函数内的一组特定行

c - 多维数组随机悬挂

python - 使用 Python/C 接口(interface)而不是 Cython 是否有优势?

c - C 中的 Realloc 分配

c - sizeof(x) 和 sizeof(p_x) 有什么区别

c - 为什么 C 中的 %f 在输出中添加了 3 个随机数?

c - 在 OS X 10.7 上使用 gcc 的 OpenSSL