op ol
op ol

Reputation: 767

Confusion about macro expansion in C

#include <stdio.h>

#define MYNUMBER 123

int main()
{
  printf("%d", MYNUMBER456);
}

Above code doesn't work because MYNUMBER and MYNUMBER456 are different token.

#include <stdio.h>

#define SECOND(a, b) printf(#a #b);
#define FIRST SECOND

int main()
{
  FIRST(hello, world!)
}

But this one works well. My thought is FIRST and FIRST(hello, world!) are different so it should not work. What am I missing?

Upvotes: 0

Views: 90

Answers (2)

Nathan Day
Nathan Day

Reputation: 6037

You can see the macro expansion by using the -E option (cc -E main.c), though you will see a lot of other stuff inserted because of your #include <stdio.h>, and without it you will probable see some default stuff inserted, in your example the main function becomes

int main()
{
  printf("hello" "world!");
}

This is because you have defined FIRST to be the same as SECOND which takes two arguments and makes them strings and since there is no comma between them they get concatenated into a single string, macros are just string substitution, in C the preprocessing is traditionally handled by a seperate executable to the compiler and is not as sophisticated as a compiler, so the type matching you would expect in most languages doesn't apply to the preprocessor.

Upvotes: 1

RDF
RDF

Reputation: 101

you are correct MYNUMBER and MYNUMBER456 are different and the pre-compiler wont know how to work with MYNUMBER456 however, when you defined FIRST as SECOND , the precompiler would expand FIRST by SECOND and then you actually have SECOND with 2 parameters so it it working

Upvotes: 1

Related Questions