Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

macro and function conflict in C

Tags:

c

function

macros

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.

like image 451
Mahesh Gupta Avatar asked Dec 02 '22 06:12

Mahesh Gupta


2 Answers

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.)

like image 198
missingfaktor Avatar answered Dec 04 '22 10:12

missingfaktor


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;
like image 31
Tim Schaeffer Avatar answered Dec 04 '22 10:12

Tim Schaeffer