首页 > 解决方案 > C中“if”语句的令人困惑和意外的行为

问题描述

我在一系列有问题的代码示例 ( http://matthieu-moy.fr/c/c_collection/ ) 中找到了这段代码,我研究这些代码是为了提高我的编程技能。您可以看到代码、我如何执行它以及下面的输出,以及我所做的一些实验。

谁能解释这个奇怪的现象?

代码

#include <stdio.h>

#define TRUE  1
#define FALSE 0

int function_returning_false() {return FALSE;}

int main() {
    if (function_returning_false) {
        printf("function returned true\n");
    }
}

建造

$ gcc Bug_Example_7.c -o Bug_Example_7_gcc

执行

$ ./Bug_Example_7_gcc

输出

function returned true

结论

可以假设“如果”条件不成立,因此程序不会打印出任何内容。但显然,一个是错误的。我已经使用 gcc (Ubuntu 9.3.0-17ubuntu1~20.04)、g++ (Ubuntu 9.3.0-17ubuntu1~20.04)、clang (10.0.0-4ubuntu1) 和在线 c 编译器 ( https://www. onlinegdb.com/online_c_compiler),都具有相同的结果:打印输出“函数返回真”。

进一步的实验表明:

用“TRUE”替换“FALSE”(参见下面的代码片段),构建它,执行它,将产生相同的打印输出(“函数返回真”)。撤消更改并再次构建并执行它不会更改输出,无论应用程序文件是否在构建之间被删除。

#include <stdio.h>

#define TRUE  1
#define FALSE 0

int function_returning_false() {return TRUE;}

int main() {
  if (function_returning_false) {
    printf("function returned true\n");
  }
}

包括stdbool-library 并将定义的“FALSE”和“TRUE”替换为“false”和“true”并没有什么区别(请参见下面的代码片段)。

#include <stdio.h>
#include <stdbool.h>

#define TRUE  1
#define FALSE 0

int function_returning_false() {return false;}

int main() {
  if (function_returning_false) {
    printf("function returned true\n");
  }
}

将“if”语句中的函数“function_returning_false()”替换为布尔值“false”(参见下面的代码片段),构建它,执行它,应用程序将没有打印输出,如预期的那样。但是,如果更改之后立即撤消并再次构建和执行代码,则应用程序将从此按应有的方式工作。删除应用程序并重新启动构建它的机器后,所描述的现象将再次出现。

#include <stdio.h>
#include <stdbool.h>

#define TRUE  1
#define FALSE 0

int function_returning_false() {return false;}

int main() {
  if (false) {
    printf("function returned true\n");
  }
}

感谢您的时间。

标签: cgccclang

解决方案


您没有正确复制程序。这是重现该错误的真实程序:

#include <stdio.h>

#define TRUE  1
#define FALSE 0

int function_returning_false() {return FALSE;}

int main() {
  if (function_returning_false) {         // note, no ()
    printf("function returned true\n");
  }
}

所以,它不是调用函数——它是把函数作为参数传递给if布尔上下文,函数总是true.


推荐阅读