Re: [Dev-C++] #DEFINE versus cont variables in array inicializations
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: <or...@vp...> - 2003-05-29 13:31:00
|
André Macário Barros wrote: > -->My questions: > 1) Is there more ways to to this? To hardcode "magic" values :) But it is not an otpion. > 2) For theese two ways presented here, when use one and when use the other? Well, C++ encourages people to use const variables instead of #define values. But I think there are circumstances, when #define is better. In particular, when you HIGHLY optimize for speed in an algorithm, and you don't want to use magic values, then it is better to use #define values, as the preprocessor replaces them (as if you had typed in the exact value) and the compiler can make various optimizations. For example, when you need to shift with a known value: i = 1<<SHIFT_VAL; This case it is better to #define SHIFT_VAL 3 for example, rather than const int SHIFT_VAL=3, because in the first case the compiler will automatically calculate the value in compile time: i = 1<<3 --> i = 8; While this is not true for using const variables (I think, unless the compiler is smart), and it takes more time to shift with a variable, rather than with a #define. So, another example: int v; v<<SHIFT_VAL; Here v is a variable, and it is faster to shift it if SHIFT_VAL is a #define, rather than if SHIFT_VAL is a variable. (I have tested this extensively!) In your case, I don't think you need this type of low-level optimisation, so I think you can safely use a const variable. Hope I could help. -- Greetings, Balázs |