Why use #define instead of a variable

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

    I got in trouble at work one time. I was accused of using "magic numbers" in array declarations.

    Like this:

    int Marylyn[256], Ann[1024];
    

    The company policy was to avoid these magic numbers because, it was explained to me, that these numbers were not portable; that they impeded easy maintenance. I argued that when I am reading the code, I want to know exactly how big the array is. I lost the argument and so, on a Friday afternoon I replaced the offending "magic numbers" with #defines, like this:

     #define TWO_FIFTY_SIX 256
     #define TEN_TWENTY_FOUR 1024
    
     int Marylyn[TWO_FIFTY_SIX], Ann[TEN_TWENTY_FOUR];
    

    On the following Monday afternoon I was called in and accused of having passive defiant tendencies.

提交回复
热议问题