Send Close Add comments: (status displays here)
Got it!  This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.nbsp; Note: This appears on each machine/browser from which this site is accessed.
C: Constants and defined literals


1. C: Constants and defined literals
In general computer science terms, a constant is a named literal.

In C, the keyword const is a modifier that tells the compiler that this variable (named memory location) cannot be changed.

2. Constant example
The following defines a constant AMAX to be used in the array a with values from 0 to AMAX+1.


3. Defined literals
Since. C (and C++) lack true constants using const, there is a small run-time efficiency loss when using constants. Thus, C and C++ (and some other languages) have a concept of defined text that is substituted into the program before the compiler gets the text.

This is known as a pre-processing step done by the preprocessor (a meta-programming process).

4. Caveats
This feature can help the programmer create machine efficient programs (and remove certain manually-created code repetition) but at the expense of making a more complicated program to develop and change - especially for the beginning programmer.

5. Defined literal
Here as a code fragment in C to defined a literal called BMAX.


6. Code example
Here is the C code.

Note then AMAX is a constant as, in C, a variable than cannot be changed while BMAX is a defined literal that is substituted into the C program by the preprocessor before the program is seen/compiled by the compiler. Here is the output of the C code.


7. Note
If you add a semicolon, that semicolon would be added into the text during the text replacement. Consider the following.
#define BMAX 10;

Then the code
   int b[BMAX+1];

would be transformed by direct text substitution by the preprocessor to the following.
   int b[10;];

This would result in a syntax compiler error. Instead, this easily made error is not allowed by the preprocessor. Since the compiler has no information about the text transformations by the preprocessor, error messages can be less meaningful and more cryptic.

The programmer must mentally keep track of the replacements in order to better identify and fix resulting compiler errors .

8. Summary
The define can make it easier to group all literals in one place, and then use const to use that define for the const literal value.

So the defined literal can be used as a constant, but the beginning (and expert) programmer may be better off using the constant feature using const - unless you know what you are doing and know that you really need this feature.

9. End of page