When to use function-like macros in C

后端 未结 6 667
心在旅途
心在旅途 2020-12-09 05:55

I was reading some code written in C this evening, and at the top of the file was the function-like macro HASH:

#define HASH(fp) (((unsigned long)fp)%NHASH)
         


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 06:41

    On one hand, macros are bad because they're done by the preprocessor, which doesn't understand anything about the language and does text-replace. They usually have plenty of limitations. I can't see one above, but usually macros are ugly solutions.

    On the other hand, they are at times even faster than a static inline method. I was heavily optimizing a short program and found that calling a static inline method takes about twice as much time (just overhead, not actual function body) as compared with a macro.

提交回复
热议问题