Considering the symbolic constants using macros,enumeration constants and const objects.
In macros scope is global and cannot be limited to local scope which is a major disadvantage.
Enumeration constants cannot be used in situations other than the integers,Enumeration constants cannot be represented in float or long.
Const objects can have local scope,can be represented in different datatypes.
But in c declaring a “int const a” or “const int a” makes the value constant and int buffer[a] is not permitted in c.. But in c++ int buffer[a] is permitted as it takes the “const a” as a compiler constant only.
Despite the disadvantages mentioned most of them generally prefer defining symbolic constants as enumeration constants rather than as const objects.
I could not understand the below statement telling that const objects cause performance penalty.How does it cause.Please help me understand..
The problem with const objects is that they may incur a performance
penalty, which enumeration constants avoid.
An object declared with
constis not a constant (more precisely, its name is not a constant expression). Theconstkeyword doesn’t mean “constant”, it means “read-only”. So given:in principal the evaluation of the
printfcall needs to fetch the value ofanswerfrom storage before passing it to theprintffunction.But in fact, any compiler worth what you pay for it (even if it’s free) will optimize the reference to
answer, so that the printf call results in the same machine code as(gcc does this with
-O1or better. If you don’t specify-O..., then the code actually fetches the value of the object – but then if you don’t ask for optimization, you’re telling the compiler you don’t care much about performance.)(A really clever compiler could generate code equivalent to
.)
The real difference is that the name
answercannot be used in contexts that require a constant expression. For example,case answer: ...would be legal in C++, but is illegal in C.Note that
int arr[answer];is actually legal, at least in C99, which allows variable-length arrays. It would be equally legal if you had writtenBut VLAs can only have automatic storage duration, so they cannot be declared at file scope or with the
statickeyword.As for the
enumtrick:that does make
answera constant expression, but it’s restricted to values of typeint(C enumeration constants are always of typeint). Some might argue that this is an abuse of theenumfeature. It is, but I don’t let that bother me.So there might be a performance penalty for
const int answer = 42;as opposed to#define answer 42, but in practice it’s just going to restrict the contexts in which you can use it.