[Solved] How does #define carries the function name in c?


C preprocessor macros simply do text replacement. They have no semantic awareness of your program.

This:

#include <stdio.h>
#define x printf("%s", f);

int main()
{ 
    char* f = "MAIN";  
    printf ("Hello World");
    x;
    return 0;
}

Becomes:

#include <stdio.h>

int main()
{ 
    char* f = "MAIN";  
    printf ("Hello World");
    printf("%s", f);;
    return 0;
}

Please note that if there is no f declared when this macro is used, you will see a compiler error. If f is declared, but is not a char *, you should see compiler warnings.

Some preprocessor macro best practices include (but are not limited to) using capitalized names, as x by convention looks like a variable or function name; and being careful about what syntactically significant symbols (in this case ;) you include in your macro text.

Hopefully this example was done for the sake of learning, because it is wholly unnecessary. Preprocessor macros wouldn’t exist if they didn’t serve a purpose, but beware they can easily obfuscate code.

1

solved How does #define carries the function name in c?