What error is thrown when macro and function conflict in C arises? Is it a macro processor error or does this error occur due to some language violation?
For example, in this code:
#include <stdio.h>
#define MAX(i, j) (i>j)? i : j
int MAX(int i, int j){
return (i>j) ? i : j;
}
int main(){
int max = MAX(5, 7);
printf("%d",max);
return 0;
}
The program throws a compile time error. But I don't understand whether it was some language violation or macro expansion error or something else.
During the preprocessing phase the code gets converted to :
int (int i>int j)? int i : int j{
return (i>j) ? i : j;
}
int main(){
int max = (5>7)? 5 : 7;
printf("%d",max);
return 0;
}
...which, as anyone can tell, is an illegal C code.
(With gcc
you could use an -E
option to see the preprocessed version of the file.)
Others have pointed out the problem but gave no solutions. The best would be to just use MAX as an inline function. If the macro is in a header, put the inline function definition in the header instead. If you still wish to use a macro (or using an old C compiler which doesn't support inline functions) you can define the function this way:
int (MAX)(int i, int j){
return (i>j) ? i : j;
}
This will prevent the troubling macro expansion and provide MAX as an external function. This will enable you to, for example, assign its address to a variable.
extern int (MAX)(int, int);
...
int (*max_func_ptr)(int, int);
...
max_func_ptr = MAX;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With