Preprocessors - C Interview Questions III


Q. What is the benefit of using #define to declare a constant?
Using the #define method of declaring a constant enables you to declare a constant in one place and use it throughout your program. This helps make your programs more maintainable, because you need to maintain only the #define statement and not several instances of individual constants throughout your program. For instance, if your program used the value of pi (approximately 3.14159) several times, you might want to declare a constant for pi as follows:
#define PI 3.14159
This way, if you wanted to expand the precision of pi for more accuracy, you could change it in one place rather than several places. Usually, it is best to put #define statements in an include file so that several modules can use the same constant value.
Using the #define method of declaring a constant is probably the most familiar way of declaring constants to traditional C programmers. Besides being the most common method of declaring constants, it also takes up the least memory. Constants defined in this manner are simply placed directly into your source code, with no variable space allocated in memory. Unfortunately, this is one reason why most debuggers cannot inspect constants created using the #define method.
Constants defined with the #define method can also be overridden using the #undef preprocessor directive. This means that if a symbol such as NULL is not defined the way you would like to see it defined, you can remove the previous definition of NULL and instantiate your own custom definition.

Q. What is the benefit of using enum to declare a constant?
Using the enum keyword to define a constant can have several benefits. First, constants declared with enum are automatically generated by the compiler, thereby relieving the programmer of manually assigning unique values to each constant. Also, constants declared with enum tend to be more readable to the programmer, because there is usually an enumerated type identifier associated with the constant's definition.
Additionally, enumerated constants can usually be inspected during a debugging session. This can be an enormous benefit, especially when the alternative has to manually look up the constant's value in a header file. Unfortunately, using the enum method of declaring constants takes up slightly more memory space than using the #define method of declaring constants, because a memory location must be set up to store the constant.
Here is an example of an enumerated constant used for tracking errors in your program:
enum Error_Code
{
     OUT_OF_MEMORY,
     INSUFFICIENT_DISK_SPACE,
     LOGIC_ERROR,
     FILE_NOT_FOUND
};

Comments