Hacker News new | past | comments | ask | show | jobs | submit login

Can you explain why this is preferable to using the preprocessor? I've always considered it a pretty fundamental principle that the "surface" interpretation of code should be as close as possible to the "real" meaning, and we're definitely not trying to represent an "enumeration". What's wrong with #define, or `const uint32_t HebrewCharMin...`?



I'd argue that in good old C, #defines for pure constants are pretty well established and considered idiomatic. In other words, I wouldn't ding it in a code review. (Nor would I ding the enum solution. Either one is perfectly cromulent.) In some ways, even though we now have better alternatives in C, I kinda feel like any C tool and any C programmer had better be able to deal with #define constants. Quickly browsing the vim source, it looks like they have seem to default to using #define for constants, and "when in Rome" is a good rule of thumb to live by. :)

On the other hand, I'm really a C++ guy, and in that domain, I'd prefer your "const uint32_t" solution. It just feels more idiomatic.

Additionally and somewhat pedantically, I prefer naming conventions that make it clear when values are a constant, so I'd use "kHebrewCharMin" or something simliar.


One thing is that the compiler can warn about missing cases when using enums (GCC optionally does this); with defines, it's not clear that several values form a closed set.

The other thing is that function signatures can now show 'enum myenum e' instead of 'int v', which is much clearer.


> One thing is that the compiler can warn about missing cases when using enums (GCC optionally does this); with defines, it's not clear that several values form a closed set.

But here, the values /don't/ form a closed set, and using enums would imply that they do.


#define is a problem in general because the compiler doesn't understand as well what is happening because the substitutions take place outside of the language's type system. Extensive preprocessor use makes writing analysis tools, refactoring IDEs, and sane compiler errors much more complicated. Const in C doesn't behave similarly to #define so it isn't really a substitute.

Note: in C++, global/static const values do behave as compile time constant expressions and are an excellent tool for this purpose.


I don't feel that there is anything "wrong," just limiting, because the C preprocessor makes it harder to use tools that walk the abstract-syntax-tree while editing code (or to analyze code). LLVM-based tools are really nice. I don't care whether it is "const uint32_t ..." or enum, or anything else, as long as it is the C/C++/ObjC language.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: