且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C 宏有什么用?

更新时间:2023-10-26 20:26:16

我最终不得不记住宏是什么,并在阅读时将其替换在脑海中.

I end up having to remember what the macro is and substitute it in my head as I read.

这似乎对宏的命名反映不佳.如果它是一个 log_function_entry() 宏,我会假设你不必模拟预处理器.

That seems to reflect poorly on the naming of the macros. I would assume you wouldn't have to emulate the preprocessor if it were a log_function_entry() macro.

我遇到的那些直观易懂的总是像小迷你函数,所以我一直想知道为什么它们不只是函数.

The ones that I have encountered that were intuitive and easy to understand were always like little mini functions, so I always wondered why they weren't just functions.

通常它们应该是,除非它们需要对泛型参数进行操作.

Usually they should be, unless they need to operate on generic parameters.

#define max(a,b) ((a)<(b)?(b):(a))

将适用于带有 < 运算符的任何类型.

will work on any type with an < operator.

不仅仅是函数,宏允许您使用源文件中的符号执行操作.这意味着您可以创建一个新的变量名称,或引用宏所在的源文件和行号.

More that just functions, macros let you perform operations using the symbols in the source file. That means you can create a new variable name, or reference the source file and line number the macro is on.

在 C99 中,宏还允许您调用可变参数函数,例如 printf

In C99, macros also allow you to call variadic functions such as printf

#define log_message(guard,format,...) 
   if (guard) printf("%s:%d: " format "
", __FILE__, __LINE__,__VA_ARGS_);

log_message( foo == 7, "x %d", x)

其中的格式类似于 printf.如果守卫为真,它会输出消息以及打印消息的文件和行号.如果它是一个函数调用,它不会知道你从中调用它的文件和行,并且使用 vaprintf 会有点更多的工作.

In which the format works like printf. If the guard is true, it outputs the message along with the file and line number that printed the message. If it was a function call, it would not know the file and line you called it from, and using a vaprintf would be a bit more work.