+ 1
#define vs. const
I recently learned about using define statements. I know that they replace every mention of what is defined before compiling. I have been told that this is more efficient. So I was wondering, which is better, using define statements or declaring constants when I want to define constants?
4 Réponses
+ 1
I guess c++ is what ur interested in due to ur tag.
The rule of thumb is not to use the preprocessor directives(#define) for ur magic number, instead use symbolic constants(constants that represents a number).
The reason is that first preprocessor directives have a file scope. So if your not careful then #define x 1 will mess up the x's in that file regardless of scope. Second preprocessor directives don't show up in the debugger making it difficult to debug ur code, and that alone is a good reason not to use them for magic numbers(or hardcoded values).
So the conclusion is you can use #define for magic numbers but it would be considered a bad way. When ur building complicated programs the debugger will be ur best friend.
+ 8
There has been quite some discussion on the topic. Not only are they entirely different in semantics, constants and macros can't really be used interchangeably. Constants are not used to tell the compiler to interpret text differently. Likewise, macros do not tell the compiler that a variable cannot be modified. There are also a lot of silly (and potentially dangerous) ways macros can be utilized, which const cannot.
https://www.sololearn.com/Discuss/1487221/?ref=app
https://www.sololearn.com/Discuss/1320385/?ref=app
https://www.sololearn.com/Discuss/240698/?ref=app
+ 3
It depends. Generally defining things as const gives the compiler more information to work with. It forces you to set the type, and the compiler can choose to in line the expression or store it in a temp variable. #define should be used for "black box" syntactic constructions which don't fit on the RHS like statements, or if you want to purposefully be vague about the type (for instance when you are targeting a specific architecture or you don't trust the type keywords). Hope this helps!
+ 1
Thanks everyone! It was very helpful!