views:

90

answers:

3

symbolic constant- no type checking->the value is just substituted
enumeration- more type safe than symbolic constant
constant variables- most type safe

Anything else that can be added here?
Any difference in terms of space occupied by these?

A: 

I would personally choose enumeration -> give you the ability to declare constants and still may be used with constructs like: XmlStatusesEnum::XML_FILE_OK.

Tomasz Kowalczyk
+1  A: 

Symbolic constants get some type checking, usually a compiler will tell you if a constant is too large to fit in the place where you assign it

Enumeration constants get no type checking at all since they are just int. In contrast to that enumeration type variables might get some type and range checking.

There is no such thing like constant variables, you probably mean const qualified variables. These are typesafe, yes, but are not constants in how C understands the word constant. Think of them better as unmutable or invariant.

Constants in the sense of C don't occupy any space, they are just symbolic values needed during compilation, there are no objects that correspond to them during execution.

Jens Gustedt
+2  A: 
  • Symbolic constants (with #define): No checking at the point of definition. Normal checking done at point of use, after textual substitution. Can be used for constants of any basic type (in C99, even for non-basic types)

  • Enumeration: Can only hold integers, and this is checked at point of definition.

  • const-qualified variables: Not really constants in C, but should be regarded as "read-only" variables. As it is not really a constant, these can't be used in places where the language requires a constant.

Variables (even if they are "read-only") should be assumed to consume memory. Enumerators and #defines can be assumed to produce constant values that are inserted directly in the code. In how far this is actually true depends also on the type of constant and the capabilities of the CPU for handling these constants.

As far as type-safety is concerned, there is not that much difference. Except that the compiler will complain more loudly if you try to initialise an enumerator with a non-integer.

In practice, enumerations are most often used for groups of integer constants that are closely related, and #defines are used for just about everything else.

Bart van Ingen Schenau
To add to this, enumerations can also allow some debuggers to display the name of the enumerated constant instead of a numerical value. Also, some compilers can treat `const`-qualified variables like a symbolic constant if can determine that its address is never computed (this would be an optimization option, not default behavior).
bta