Why would someone use #define to define constants?

前端 未结 9 1691
星月不相逢
星月不相逢 2020-11-27 04:02

It\'s simple question but why would someone use #define to define constants?

What\'s the difference between

#define sum 1 and const int su

9条回答
  •  自闭症患者
    2020-11-27 04:11

    For the example that you just gave, I would normally use a const. Except of course, the #define can be used for conditional compilation elsewhere:

    #if SOME_DEFINE == 1
        // Conditional code
    #endif
    

    This is something you can't do with a const. If you don't need the value to be accessible from the preprocessor, I'd say use a const unless there's some reason why that's not possible. There's some stuff on this in the C++ FAQ lite, where they rightly point out that just because the preprocessor is "evil", it doesn't mean you'll never need it.

提交回复
热议问题