开发者

#define vs enum in an embedded environment (How do they compile?)

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!


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.


An enum is just an integer, ultimately. The compiler propagates the values, just as it would for a const.


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:

  1. you actually need the efficiency boost
  2. the part of the program you're changing has been shown to be a bottleneck by a profiler.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜