Why would someone use #define to define constants?

前端 未结 9 1703
星月不相逢
星月不相逢 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:15

    From Introduction to programming with C++ which was written by Daniel Liang stated that:

    When you define a constant using #define directive, the constant is not stored in memory.The constant will be replaced with a value by compiler. When you declare constant using const keyword, the constant is stored in memory just like variable.

    If constant need to be used in multiple programs, use #define to define it in header file so it can be included in other program. If constant used only in one program, using const to declare is more efficient.

提交回复
热议问题