Pergunta

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!

Foi útil?

Solução

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.

Outras dicas

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.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top