Home > Software design >  Function like macro passed as an argument. Compiler error coming [closed]
Function like macro passed as an argument. Compiler error coming [closed]

Time:09-17

When I am passing a function like macro as an argument to another function having declared as a function pointer argument. I am not able to run the code getting compile time error.

#include <stdio.h> 
#define print_numbers() (void (0)) 

void display(void (*p)()) 
{ 
    for(int i=1;i<=5;i  ) 
    { 
        p(); 
    }
} 

int main() { 
    void (*p)(int); // void function pointer declaration 
    printf("The values are :"); 
    display(print_numbers); return 0; 
} 

Error

prog.c: In function ‘main’: prog.c:16:13: error: ‘print_numbers’ undeclared (first use in this function) 
    display(print_numbers); 
            ^ 
prog.c:16:13: note: each undeclared identifier is reported only once for each function it appears in

CodePudding user response:

"Function like macro" means that the macro works like a function. It does not mean that it is a function. You cannot pass a macro like that.

CodePudding user response:

Function macros are expanded only if they are used like function. Therefore only print_numbers() will expand to (void(0)) while print_numbers will not.

If you want it to expand define the macro as:

#define print_numbers (void (0)) 

The question if the resulting code compiles is a separate topic.


EDIT

However it is possible to pass a function-like macro to another function-like macro. Just make display be a macro rather than a function.

#define display(p) for(int i=1;i<=5;i  ) p()

Now display(print_numbers) will expand to

for(int i=1;i<=5;i  ) (void (0));
  • Related