www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - enum vs const int

reply Lucas Goss <lgoss007 gmail.com> writes:
I'm working on X headers and I have a file with a lot of this:

#define XK_BackSpace 0xff08
#define XK_Tab       0xff09
#define XK_Linefeed  0xff0a
...

Well with the recent mention of size of D programs on this newsgroup, I 
decided to do a little test. I converted around 500 - 600 lines of code 
(all #define like above with some comments in between), to const uint, 
checked size, then converted those lines to using enums and checked 
size. The documentation says that enums define constants in a manner 
equivalent to: const int A = 0; ... So I was kinda surprised to find that:

#define->const uint = 246.5K
#define->enum       = 233.1K

So... It's better to use enum's? Is this by design? And if the whole 
file is just #define's like above, should it just be one big enum? Or 
multiple enum's?
Mar 21 2006
parent reply Sean Kelly <sean f4.ca> writes:
Lucas Goss wrote:
 I'm working on X headers and I have a file with a lot of this:
 
 #define XK_BackSpace 0xff08
 #define XK_Tab       0xff09
 #define XK_Linefeed  0xff0a
 ...
 
 Well with the recent mention of size of D programs on this newsgroup, I 
 decided to do a little test. I converted around 500 - 600 lines of code 
 (all #define like above with some comments in between), to const uint, 
 checked size, then converted those lines to using enums and checked 
 size. The documentation says that enums define constants in a manner 
 equivalent to: const int A = 0; ... So I was kinda surprised to find that:
 
 #define->const uint = 246.5K
 #define->enum       = 233.1K
 
 So... It's better to use enum's? Is this by design? And if the whole 
 file is just #define's like above, should it just be one big enum? Or 
 multiple enum's?
For header conversion, I agree with Don's suggestion that #defines should be converted to auto declarations. ie. const auto XK_BackSpace = 0xff08; const auto XK_Tab = 0xff09; const auto XK_Linefeed = 0xff0a; I think this has the benefit of being more maintainable and more in line with the original semantics. The executable size issue is a bit odd though. Perhaps the optimizer deals better with enums than with const variables? Sean
Mar 21 2006
parent Lucas Goss <lgoss007 gmail.com> writes:
Sean Kelly wrote:
 For header conversion, I agree with Don's suggestion that #defines 
 should be converted to auto declarations.  ie.
Hmm, I never thought about that, I must have missed that suggestion, but it makes sense.
 ... The executable size issue is a bit odd 
 though.  Perhaps the optimizer deals better with enums than with const 
 variables?
Yeah auto is the same way as const uint (both are 246.5K). The original without the import is 233.0K, so the enum is only 0.1K more. Oh and I don't know if it makes a difference but I didn't use any values from the imported file, I just put the import statement in and recompiled.
Mar 21 2006