Reputation: 4275
This question has been done to death, and I would agree that enums are the way to go. However, I am curious as to how enums compile in the final code- #defines are just string replacements, but do enums add anything to the compiled binary? Or are they both equivalent at that stage. When writing firmware and memory is very limited, is there any advantage, no matter how small, to using #defines?
Thanks!
EDIT: As requested by the comment below, by embedded, I mean a digital camera.
Thanks for the answers! I am all for enums!
Upvotes: 7
Views: 3945
Reputation: 9135
It's impossible to say without profiling or measuring in some other manner.
BUT, any decent compiler will not show any significant difference. Furthermore, you should always prefer readable, typesafe code over efficient, unreadable, gotcha-ridden code. Don't start optimizing for efficiency over readability until you have proven two things:
Upvotes: 4
Reputation: 215211
Both are constant expressions in the terminology of the standard, so they "should" be evaluated fully at compile-time by any sane compiler. It would take a maliciously pathological compiler to generate different code.
Upvotes: 10
Reputation: 37930
An enum
is just an integer, ultimately. The compiler propagates the values, just as it would for a const
.
Upvotes: 5