Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke function instead of macro in C

Tags:

c

macros

My question is: If you have a macro and a function with the same name, only the macro would be invoked, right? What if I want to invoke the function instead of the macro?

like image 833
bookishq Avatar asked Mar 27 '13 07:03

bookishq


People also ask

Can I call function in C through macro?

In C, function-like macros are much similar to a function call. In this type of macro, you can define a function with arguments passed into it.

Why use a macro instead of a function?

Speed versus size The main benefit of using macros is faster execution time. During preprocessing, a macro is expanded (replaced by its definition) inline each time it is used. A function definition occurs only once regardless of how many times it is called.

Can I call a function in a macro?

Just type the word Call then space, then type the name of the macro to be called (run). The example below shows how to call Macro2 from Macro1. It's important to note that the two macros DO NOT run at the same time.


1 Answers

If you have a function and a function-like macro both named foo and want to invoke the function version, you can do:

(foo)(args)

This works because function-like macro names must be followed by a parenthesized argument list for substitution to occur.

This is mentioned in section 7.1.4/1 of the ISO C99 standard:

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. Any macro definition of a function can be suppressed locally by enclosing the name of the function in parentheses, because the name is then not followed by the left parenthesis that indicates expansion of a macro function name. 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.

If you need to do this, though, you probably should add comments to your code explaining it since it looks a little weird and isn't common practice. If feasible, renaming the function to avoid the name collision might be more maintainable in the long run.

like image 199
jamesdlin Avatar answered Sep 19 '22 13:09

jamesdlin