简体   繁体   English

何时使用预处理器在C中定义函数?

[英]When to use the preprocessor to define functions in C?

When should I use the C preprocessor to define a function? 什么时候应该使用C预处理器定义函数? Here's a quick example: 这是一个简单的示例:

#define isUnderscore(ch) ((ch) == '_')

Over this: 在此:

// just to make the bool more clear.
typedef enum {
    false, true
} bool;

bool isUnderscore(char x) {
    return x == '_';
}

This may be a stupid question, but I can't find any results from a quick Google. 这可能是一个愚蠢的问题,但我无法从快速的Google找到任何结果。

You normally use the preprocessor if you want to discard type-safety. 如果要舍弃类型安全性,通常可以使用预处理器。 isUnderscore as a macro will accept any type for ch for which == makes sense. isUnderscore作为宏将接受ch ==有意义的任何类型。

As a rule of thumb, don't use the preprocessor unless absolutely necessary: debugging functions implemented as preprocessor macros is difficult. 根据经验,除非绝对必要,否则不要使用预处理器:调试作为预处理器宏实现的功能很困难。

(Remember that function overloading is not available in C). (请记住,函数重载在C中不可用)。

Starting from C99 you could write it as inline function: 从C99开始,您可以将其编写为inline函数:

#include <stdbool.h>

inline bool isUnderscore(char x) {
    return x == '_';
}

This gives you both safety and type-checking of normal functions as well as efficiency of function-like macros (though there is not guarantee on that). 这为您提供了正常功能的安全性和类型检查,以及类似功能的宏的效率(尽管不能保证)。

From N1570 (C11 draft) 6.7.4/6 Function specifiers (with emphasis mine): 来自N1570(C11草案) 6.7.4/6 功能说明符 (重点是我的):

A function declared with an inline function specifier is an inline function . inline函数说明符声明的函数是内联函数 Making a function an inline function suggests that calls to the function be as fast as possible. 使函数成为内联函数意味着对函数的调用应尽可能快。 138) The extent to which such suggestions are effective is implementation-defined . 138)这些建议有效的程度是实施定义的 139) 139)

The general rule is if you can do something in the language itself rather than the preprocessor then you should. 一般规则是,如果您可以使用语言本身而不是预处理器来执行某些操作,则应该这样做。

A few decades ago there might have been a performance improvement where the macro would be inline, but any compiler that you're likely to use will be do these trivial optimisations. 几十年前,宏可能是内联的,但性能可能有所提高,但是您可能使用的任何编译器都会进行这些琐碎的优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM