c - 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");
}
}
感谢您的时间。
解决方案
您没有正确复制程序。这是重现该错误的真实程序:
#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
.
推荐阅读
- java - 如何使用 SharedPreferences 存储布尔值?
- file - 尝试获取一些脚本以根据文件名的前 4 个字符将 pdf 文件移动到文件夹中
- java - Spring-batch 没有得到属性 spring.batch.table-prefix
- excel - 我陷入了无限循环
- javascript - 如何从前端(ejs/html)调用restapi函数
- c# - WinAppDriver - FindElementsByName / FindElementsByAccessibilityId 花费的时间越来越多,并且随时间线性增加
- php - Eloquent - 如何在没有观察者的情况下等到 create() 之后
- php - 网关响应在子目录 wordpress 安装中不起作用
- go - 如何使用 Sarama Go Kafka Consumer 从最新的偏移量中消费
- react-native - “create-react-app my-app”无法识别