c - 奇怪的 while() 条件

标签 c

任何人都可以帮助我理解以下 while() 循环中的条件编写方式:

请找到下面的代码:

int fun () {
    static int x = 5;
    x--;
    pritnf("x = %d\n", x);
    return x;
}

int main () {
  do {
    printf("Inside while\n");
  } while (1==1, fun());

  printf("Main ended\n");
  return 0;
}

Output:

Inside while
x = 4
Inside while
x = 3
Inside while
x = 2
Inside while
x = 1
Inside while
x = 0
Main ended

我还有以下代码和令人惊讶的输出:

int fun () {
    static int x = 5;
    x--;
    printf("x = %d\n", x);
    return x;
}

int main () {
  do {
    printf("Inside while\n");
  } while (fun(),1==1);

  printf("Main ended\n");
  return 0;
}

Output:


Inside while
x = 4
Inside while
x = 3
Inside while
x = 2
Inside while
x = 1
Inside while
x = 0
Inside while
x = -1
Inside while
x = -2
Inside while
x = -3

.
.
.
.

    Inside while
x = -2890
Inside while
x = -2891
Inside while
x = -2892
Inside while
x = -2893
Inside wh
Timeout

根据我的理解,条件是从右到左检查的。如果 1==1 出现在右侧,则条件始终为 true,并且 while 永远不会中断。

最佳答案

, 是一个运算符,它接受两个参数并返回第二个参数。

在第一种情况1==1,fun()相当于fun(),因此循环发生在fun() > 返回一个非零数字。

在第二种情况下,fun(), 1==1 永远发生(因此超时)。

关于c - 奇怪的 while() 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33909325/

相关文章:

c - ws ://in a C program

c - 排序结构不起作用

c - 如何将数据插入到C中的csv文件的同一行中?

c - 将linux C代码移植到windows

在 C 中调用相同顺序的函数,每次调用一个不同的函数。如何更优雅地实现?

无法增加指针位置

c - 如何在 SIGSEGV 上使用 _Unwind_Backtrace 获取 fullstacktrace

C 非标准库

C89 与 c99 GCC 编译器

c++ - 从 WINAPI 获取文件的先前版本