scope of preprocessor definition

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sivajyothi
    New Member
    • Aug 2014
    • 1

    scope of preprocessor definition

    Code:
    #include<stdio.h>
    #define a 10
    void foo(void);
    main( )
    {
    printf("%d\n", a);
    foo( );
    printf("%d\n", a);
    }
    void foo(void)
    {
    #undef a
    #define a 50
    }
    Why it is producing output as
    10
    10
    instead of
    10
    50
    Last edited by Rabbit; Aug 6 '14, 03:28 PM. Reason: Please use [code] and [/code] tags when posting code or formatted data.
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    The program-build process is equivalent to the following:
    1. First the preprocessor translates your source and header files into an intermediate file.
    2. Then the compiler translates that intermediate file into an object file.
    3. Then the linker combines one or more object files and object libraries into an executable file.
    4. Sometime later, you run the executable file.

    A particular compiler implementation might not generate all of these intermediate files, but it will act as if it did. Some compilers can be induced to preserve the intermediate file produced by the preprocessor so you can look at it.

    The "scope" of a preprocessor macro (it is not a variable) is all of the lines between its #define and its #undef. The things that affect variable scope (such as function definitions and braces) have no effect on preprocessor macros.

    You expected execution of function foo to change the value of macro a. In actuality, all of the preprocessor directives and macros have been fully expanded before the code is compiled. The compiler and executable have no awareness that there is such a thing as a preprocessor.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      To be clear about this:

      Code:
      #define a 10
      tells the preprocessor to change all occurrences of a to 10. Later if you define a as something else, thoss 10's are still there.

      Comment

      Working...