Macro Preprocessor, what is actually happening in here?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Adrian20XX
    New Member
    • Feb 2008
    • 11

    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
    [code=c]#include <stdio.h>

    #define FIRST 4

    #define StateStart(n) (STATE##n##_STA RT)

    #define STATE0_START (FIRST)
    #define STATE1_START (STATE0_START+5 )

    main()
    {
    printf("State 0 start: %d\n", STATE0_START);
    printf("State 1 start: %d\n", STATE1_START);
    printf("State 0 start: %d\n", StateStart(0));
    printf("State 1 start: %d\n", StateStart(1));
    }
    [/code]
    Second Version: Does not compile

    Error: warning C4013: 'StateStart' undefined; assuming extern returning int
    [code=c]
    #include <stdio.h>

    #define FIRST 4

    #define StateStart(n) (STATE##n##_STA RT)

    #define STATE0_START (FIRST)
    #define STATE1_START (StateStart(0)+ 5)

    main()
    {
    printf("State 0 start: %d\n", STATE0_START);
    printf("State 1 start: %d\n", STATE1_START);
    printf("State 0 start: %d\n", StateStart(0));
    printf("State 1 start: %d\n", StateStart(1));
    }[/code]
    Last edited by sicarie; Feb 26 '08, 03:38 PM. Reason: Code tags make annoying formatting (like bold) unnecessary
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    This is the translation unit I got from Visual Studio.NET 2005:
    [code=cpp]
    main()
    {
    printf("State 0 start: %d\n", (4));
    printf("State 1 start: %d\n", (((4))+5));
    printf("State 0 start: %d\n", ((4)));
    printf("State 1 start: %d\n", ((StateStart(0) +5)));
    }
    [/code]

    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.

    Comment

    Working...