Why use #define instead of a variable

后端 未结 8 1389
清酒与你
清酒与你 2020-12-04 06:19

What is the point of #define in C++? I\'ve only seen examples where it\'s used in place of a \"magic number\" but I don\'t see the point in just giving that val

相关标签:
8条回答
  • 2020-12-04 06:36

    The #define is part of the preprocessor language for C and C++. When they're used in code, the compiler just replaces the #define statement with what ever you want. For example, if you're sick of writing for (int i=0; i<=10; i++) all the time, you can do the following:

    #define fori10 for (int i=0; i<=10; i++)
    
    // some code...
    
    fori10 {
        // do stuff to i
    }
    

    If you want something more generic, you can create preprocessor macros:

    #define fori(x) for (int i=0; i<=x; i++)
    // the x will be replaced by what ever is put into the parenthesis, such as
    // 20 here
    fori(20) {
        // do more stuff to i
    }
    

    It's also very useful for conditional compilation (the other major use for #define) if you only want certain code used in some particular build:

    // compile the following if debugging is turned on and defined
    #ifdef DEBUG
    // some code
    #endif
    

    Most compilers will allow you to define a macro from the command line (e.g. g++ -DDEBUG something.cpp), but you can also just put a define in your code like so:

    #define DEBUG
    

    Some resources:

    1. Wikipedia article
    2. C++ specific site
    3. Documentation on GCC's preprocessor
    4. Microsoft reference
    5. C specific site (I don't think it's different from the C++ version though)
    0 讨论(0)
  • 2020-12-04 06:41

    The #define allows you to establish a value in a header that would otherwise compile to size-greater-than-zero. Your headers should not compile to size-greater-than-zero.

    // File:  MyFile.h
    
    // This header will compile to size-zero.
    #define TAX_RATE 0.625
    
    // NO:  static const double TAX_RATE = 0.625;
    // NO:  extern const double TAX_RATE;  // WHAT IS THE VALUE?
    

    EDIT: As Neil points out in the comment to this post, the explicit definition-with-value in the header would work for C++, but not C.

    0 讨论(0)
提交回复
热议问题