Thread: Scope of macros

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    28

    Scope of macros

    While this is written in K & R "The scope of a name defined with #define is from its point of definition to the end of the source file being compiled."

    Why this piece of code is working fine ?

    Code:
    #include <stdio.h>
    
    #define MAX MAXX
    #define MAXX 10
    
    int main() {
        printf("%d", fun());
        return 0;
    }
    
    
    int fun() {
        return MAX;
    }
    and why this code is showing error ?

    Code:
    #include <stdio.h>
    
    #define MAXX 10
    #define MAX MAXX
    #undef MAXX
    
    
    int main() {
        printf("%d", fun());
        return 0;
    }
    
    
    int fun() {
        return MAX;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > and why this code is showing error ?
    Because line 4 isn't transformed into
    #define MAX 10
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Quote Originally Posted by _arjun View Post
    "The scope of a name defined with #define is from its point of definition to the end of the source file being compiled."
    If you use #undef SYMBOL then you are ending the scope of SYMBOL

    Quote Originally Posted by _arjun View Post
    and why this code is showing error ?

    Code:
    #include <stdio.h>
    
    #define MAXX 10
    #define MAX MAXX
    #undef MAXX
    
    int fun() {
        return MAX;
    }
    
    int main() {
        printf("%d", fun());
        return 0;
    }
    The replacements only affect the code lines, not the preprocessor lines. Try the following instead:

    Code:
    #include <stdio.h>
    
    #define MAXX 10
    const int MAX=MAXX;
    #undef MAXX
    
    int fun() {
        return MAX;
    }
     
    int main() {
        printf("%d", fun());
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Macros inside of macros
    By Chewie8 in forum C Programming
    Replies: 2
    Last Post: 02-24-2008, 03:51 AM
  2. Macros
    By jsbeckton in forum C Programming
    Replies: 11
    Last Post: 12-02-2005, 02:10 AM
  3. macros
    By rpc2005 in forum C Programming
    Replies: 23
    Last Post: 06-14-2005, 08:56 AM
  4. macros
    By Chaplin27 in forum C++ Programming
    Replies: 7
    Last Post: 03-02-2005, 01:06 PM
  5. Min and Max Macros
    By Batman.......hehehehe in forum C++ Programming
    Replies: 2
    Last Post: 07-09-2002, 01:14 PM

Tags for this Thread