c - 为什么#define 不需要分号?

标签 c c-preprocessor

我正在用 C 编写一些测试代码。我错误地在 #define 之后插入了 ;,这给了我错误。为什么 #define 不需要分号?

更具体地说:

方法一:有效

const int MAX_STRING = 256;

int main(void) {
    char buffer[MAX_STRING];
}

方法 2:不起作用 - 编译错误。

#define MAX_STRING 256;

int main(void) {
    char buffer[MAX_STRING];
}

这些代码行为不同的原因是什么?这两个 MAX_STRING 不是常量吗?

最佳答案

#define MAX_STRING 256;

意思是:

只要在预处理时发现 MAX_STRING,就将其替换为 256;。在您的情况下,它将采用方法 2:

#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING 256;

int main(void) {
    char buffer [256;];
}

这不是有效的语法。替换

#define MAX_STRING 256;

#define MAX_STRING 256

两个代码之间的区别在于,在第一个方法中,您声明了一个等于 256 的常量,但在第二个代码中,您定义了 MAX_STRING 来代表 256 ; 在你的源文件中。

The #define directive is used to define values or macros that are used by the preprocessor to manipulate the program source code before it is compiled. Because preprocessor definitions are substituted before the compiler acts on the source code, any errors that are introduced by #define are difficult to trace.

语法是:

#define CONST_NAME VALUE

如果末尾有;,则认为是VALUE的一部分。

要了解 #define 的工作原理,请尝试定义:

#define FOREVER for(;;)
...
    FOREVER {
         /perform something forever.
    }

John Hascall 的有趣评论:

Most compilers will give you a way to see the output after the preprocessor phase, this can aid with debugging issues like this.

gcc它可以通过标记 -E 来完成。

关于c - 为什么#define 不需要分号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58573204/

相关文章:

c++ - cudaMemcpyDeviceToHost() 失败

c++ - 声明 2 数组时堆栈溢出

c - 在两个源文件之间拆分类似函数的宏调用

C++ 预处理器标准行为

c - 内联方法名称的 GCC 预处理器

c - 在将宏作为参数传递给另一个宏之前,按值转换宏

C Pthreads 问题,无法传递我想要的信息?

c - C 内核级多线程

c++ - 您可以将#define 扩展为字符串文字吗?

c - 我的程序没有将输入数据存储到 C 中的结构中