c - Why is it sometimes valid to write an include statement in a codeblock?
问题描述
I amcoming from a python background, where the following is valid:
def f():
import someLibrary
someLibrary.libraryFunction()
So when I needed to debug C code, I wrote, in the middle of my function:
void f(int param)
{
int status;
/* other code */
#include <stdio.h>
printf("status: %d", status);
/* more code */
}
And it compiled and worked as I expected. Later it was pointed out to me that this shouldn't compile, since the C pre-processor literally replaces the #include~ statement with the contents of
stdio.h`.
So why was this valid code?
解决方案
有人向我指出这不应该编译,因为 C 预处理器实际上用stdio.h 的内容替换了#include 语句。
这上面的逻辑没有道理。仅仅因为预处理器从stdio.h
文件中插入文本并不意味着它不应该编译。如果该文件中没有任何会导致编译错误的内容,那么它将编译得很好。
此外,标头中通常有一个多重包含保护。因此,如果它们之前已经包含在内,则任何进一步尝试包含它都无效。在这种情况下,如果<stdio.h>
之前已经包含在文件中(直接或间接),则#include
将无效。
话虽如此,但不要这样做。在 C 中,标准头文件不应该包含在函数范围内。
推荐阅读
- android - Android 4.0.4 上的 Android 短信限制
- angular - 角 | 互联网浏览器 | 焦点和设置光标到输入字段
- ruby-on-rails - Vue axios 将数组作为参数传递给 Rails 并更新所有(批量编辑)
- css - CSS网格项目退出网格s 但正确地与s
- apache-kafka - 从 changelog kafka topic 恢复 StateStore 时 kafka 流处理器的状态
- c++ - 以类对象为成员的类成员初始化顺序
- python - LSTM 训练期间的持续损失 - PyTorch
- excel - 为表格的所有现有/新行设置特定高度
- python-3.x - 我正在尝试在使用边界矩形的最小区域应用透视变换后裁剪图像
- c# - 无法检索目标数据库架构 - Visual Studio 错误