Are there any restrictions to the C standard allowing functions to be implemented as macros?

前端 未结 2 1863
栀梦
栀梦 2021-01-18 12:50

Often, in addition to providing a function declaration, C standard headers may provide a \"masking macro\" to make things speedier. For example, if I include ctype.h<

2条回答
  •  离开以前
    2021-01-18 13:33

    Per C11 7.1.4.1, "Use of Library Functions", particularly the last part quoted below:

    Any function declared in a header may be additionally implemented as a function-like macro defined in the header, so if a library function is declared explicitly when its header is included, one of the techniques shown below can be used to ensure the declaration is not affected by such a macro....For the same syntactic reason, it is permitted to take the address of a library function even if it is also defined as a macro. The use of #undef to remove any macro definition will also ensure that an actual function is referred to. Any invocation of a library function that is implemented as a macro shall expand to code that evaluates each of its arguments exactly once, fully protected by parentheses where necessary, so it is generally safe to use arbitrary expressions as arguments.

    Note that the "generally" at the end is important, there, and there are explicit exceptions. C11 7.21.7.5.2 says "the getc function is equivalent to fgetc, except that if it is implemented as a macro, it may evaluate stream more than once, so the argument should never be an expression with side effects", with similar language for putc in C11 7.21.7.7.2. In this particular case, stream is a FILE *, so under normal circumstances it would be kind of weird to have this as an expression with side-effects, but it could happen. The same is also true for their wide character counterparts, putwc() and getwc(). I am not aware of any other exceptions like this.

提交回复
热议问题