Order of execution of preprocessor macros

This is a discussion on Order of execution of preprocessor macros within the C Programming forums, part of the General Programming Boards category; Hello, Is there a rule to the effect that preprocessor macros involving the # and ## operators are executed before ...

  1. #1
    DL1
    DL1 is offline
    Registered User
    Join Date
    Jun 2008
    Location
    Somewhere in Europe
    Posts
    99

    Order of execution of preprocessor macros

    Hello,

    Is there a rule to the effect that preprocessor macros involving the # and ## operators are executed before other macros? For example, the following program

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    #define X 1
    #define Y 3
    #define Z surprise
    
    #define r(a, b) a##b
    #define s(c) #c
    
    int main()
    {
        printf("%d\n", r(X, Y));
        printf("%s\n", s(Z));
        return 0;
    }
    yields a compilation error message "error: 'XY' undeclared". I take it that this means the fourth macro concatinated the X and Y before the first two macros had a chance to substitute for them.

    If the first printf() is commented out and the program is compiled and run, the output is "Z". That suggests that fifth macro has stringised the Z before the third macro substituted for it.

    This sort of suprises me, as I had assumed the macros would be executed in the order in which they appeared in the code.

    Can anyone shed any light on what is going on here?

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    They are replaced in the order they are encountered. It encounters r before it encounters X.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    DL1
    DL1 is offline
    Registered User
    Join Date
    Jun 2008
    Location
    Somewhere in Europe
    Posts
    99
    Of course. Now it makes sense. Thanks a lot.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. order of execution of tokens in a c++ source code
    By sandy.sandipanc in forum C++ Programming
    Replies: 4
    Last Post: 10-04-2008, 12:34 PM
  2. Weird code execution order problem
    By Syko in forum C Programming
    Replies: 2
    Last Post: 05-12-2005, 02:29 PM
  3. expression execution order
    By _Elixia_ in forum C Programming
    Replies: 3
    Last Post: 10-02-2003, 04:01 PM
  4. uncertainty in order of execution - any explanation?
    By ylzhang in forum C Programming
    Replies: 6
    Last Post: 05-31-2003, 08:04 AM
  5. randomizing order of execution of function
    By y2jasontario in forum C Programming
    Replies: 2
    Last Post: 04-03-2002, 06:50 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21