Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why define a function prototype, then preprocessor macro with the same name?

I'm reading a book about C, and somewhere in the authors code I found a definition of a function prototype, then a macro with the same name, and there is no definition of the function itself neither in any .h or .c file.

I mean something like that:

int print_my_stufff(char *stuff);
#define print_my_stuff(A) (printf("%s\n", A))
/* and print-my-stuff() function never defined anywhere else */

The code works, but i just don't get why he needed a function prototype in the first place? Couldn't he just write a macro? What's the point? Is it to tell a compiler that a macro should be evaluated to an expression which returns int or what? Removing the prototype doesn't seems to change a behavior. The author didn't explain this.

like image 489
coredump Avatar asked Dec 24 '15 04:12

coredump


1 Answers

This is an outdated practice, from before inline functions. If you call the function as in print_my_stuff("hello"), then the preprocessor will see the call syntax and insert the contents of the macro. If you use the name otherwise, as in f_ptr = &print_my_stuff, the compiler will use the actual function.

Calling the function as (print_my_stuff)("hello") will also bypass the macro. Some paranoid style guides even require parenthesizing certain function names because Macros Are Evil.

like image 50
Potatoswatter Avatar answered Oct 19 '22 08:10

Potatoswatter