gpt4 book ai didi

c - #undef-ing 在实践中?

转载 作者:太空狗 更新时间:2023-10-29 16:33:08 25 4
gpt4 key购买 nike

我想知道#undef 在 C 中的实际用途。我正在通过 K&R 工作,并且正在处理预处理器。其中大部分是我(或多或少)理解的 Material ,但第 90 页(第二版)上的某些内容让我印象深刻:

Names may be undefined with #undef, usually to ensure that a routine is really a function, not a macro:

#undef getchar

int getchar(void) { ... }

这是防御某人 #define 与您的函数同名的宏的常见做法吗?或者这真的更多的是现实中不会出现的样本? (EG,没有人在他的正确、错误或疯狂的头脑中应该重写 getchar(),所以它不应该出现。)有了你自己的函数名称,你觉得有必要这样做吗?如果您正在开发供其他人使用的库,这会改变吗?

最佳答案

它做什么

如果您阅读 Plauger 的 The Standard C Library (1992),你会看到 <stdio.h> header 允许提供 getchar()getc()作为类似函数的宏(具有 getc() 的特殊权限,可以多次评估其文件指针参数!)。但是,即使它提供了宏,实现也有义务提供执行相同工作的实际函数,主要是为了您可以访问一个名为 getchar() 的函数指针。或 getc()并将其传递给其他函数。

也就是说,通过做:

#include <stdio.h>
#undef getchar

extern int some_function(int (*)(void));

int core_function(void)
{
int c = some_function(getchar);
return(c);
}

正如所写,core_function()毫无意义,但它说明了这一点。你可以用 isxxxx() 做同样的事情<ctype.h> 中的宏也是,例如。

通常,您不想这样做 - 您通常不想删除宏定义。但是,当你需要真正的功能时,你可以得到它。提供库的人可以很好地模拟标准C库的功能。

很少需要

另请注意,您很少需要使用显式 #undef 的原因之一是因为您可以通过编写调用函数而不是宏:

int c = (getchar)();

因为getchar之后的token不是 ( , 它不是类函数宏的调用,所以它必须是函数的引用。同样,上面的第一个示例即使没有 #undef 也能正确编译和运行。 .

如果您使用宏覆盖实现您自己的函数,您可以使用它来获得良好的效果,尽管除非解释,否则它可能会有点困惑。

/* function.h */

extern int function(int c);
extern int other_function(int c, FILE *fp);
#define function(c) other_function(c, stdout);

/* function.c */



/* Provide function despite macro override */
int (function)(int c)
{
return function(c, stdout);
}

函数定义行不调用宏,因为 function 之后的标记不是 ( . return行确实调用了宏。

关于c - #undef-ing 在实践中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/216865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com