Why use #define instead of a variable

后端 未结 8 1420
清酒与你
清酒与你 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: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.

提交回复
热议问题