469,641 Members | 1,129 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,641 developers. It's quick & easy.

Macro Preprocessor, what is actually happening in here?

Hi,

I don't understand why the first C (c, not c++) program compiles and the second one does not compile.

Any idea what is happening with the macro pre-processor in here, why StateStart(0) can be used in the printf statement, but not in the #define?

TIA & Regards ...

First version: compiles
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. #define FIRST 4
  4.  
  5. #define StateStart(n) (STATE##n##_START)
  6.  
  7. #define STATE0_START (FIRST)
  8. #define STATE1_START (STATE0_START+5)
  9.  
  10. main()
  11. {
  12.     printf("State 0 start: %d\n", STATE0_START);
  13.     printf("State 1 start: %d\n", STATE1_START);
  14.     printf("State 0 start: %d\n", StateStart(0));
  15.     printf("State 1 start: %d\n", StateStart(1));
  16. }
  17.  
Second Version: Does not compile

Error: warning C4013: 'StateStart' undefined; assuming extern returning int
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. #define FIRST 4
  4.  
  5. #define StateStart(n) (STATE##n##_START)
  6.  
  7. #define STATE0_START (FIRST)
  8. #define STATE1_START (StateStart(0)+5)
  9.  
  10. main()
  11. {
  12.     printf("State 0 start: %d\n", STATE0_START);
  13.     printf("State 1 start: %d\n", STATE1_START);
  14.     printf("State 0 start: %d\n", StateStart(0));
  15.     printf("State 1 start: %d\n", StateStart(1));
  16. }
Feb 26 '08 #1
1 1194
weaknessforcats
9,208 Expert Mod 8TB
This is the translation unit I got from Visual Studio.NET 2005:
Expand|Select|Wrap|Line Numbers
  1. main()
  2. {
  3.     printf("State 0 start: %d\n", (4));
  4.     printf("State 1 start: %d\n", (((4))+5));
  5.     printf("State 0 start: %d\n", ((4)));
  6.     printf("State 1 start: %d\n", ((StateStart(0)+5)));
  7. }
  8.  
A StateStart(1) generates the token STATE1_START and that symbol is defined as (StateStart(0)+5). So that's what you get.

There is no rescan after a macro expansion unless a ## operator or a #define was involved and here none were so StateStart(0) was not seen as a macro.

You now die in the link with an unresolved external reference to StateStart.
Feb 26 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by John H. Krueckeberg | last post: by
3 posts views Thread by John | last post: by
3 posts views Thread by Charlie Zender | last post: by
3 posts views Thread by Chris Saunders | last post: by
17 posts views Thread by ethan | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.