What is the difference between constants defined through #define and the constant keyword?


A constant is similar to a variable in the sense that it represents a memory location (or simply, a value). It is different from a normal variable, in that it cannot change it's value in the proram - it must stay for ever stay constant. In general, constants are a useful because they can prevent program bugs and logical errors(errors are explained later). Unintended modifications are prevented from occurring. The compiler will catch attempts to reassign new values to constants.
Constants may be defined using the preprocessor directive #define. They may also be defined using the const keyword.
So whats the difference between these two?

#define ABC 5
and
const int abc = 5;

There are two main advantages of the second one over the first technique. First, the type of the constant is defined. "pi" is float. This allows for some type checking by the compiler. Second, these constants are variables with a definite scope. The scope of a variable relates to parts of your program in which it is defined.
There is also one good use of the important use of the const keyword. Suppose you want to make use of some structure data in some function. You will pass a pointer to that structure as argument to that function. But to make sure that your structure is readonly inside the function you can declare the structure argument as const in function prototype. This will prevent any accidental modification of the structure values inside the function




And also read
1.    Do Global variables start out as zero? 
2.    Does C have boolean variable type?
3.    Where may variables be defined in C?
4.    To what does the term storage class refer? What are auto, static, extern, volatile, const classes?
5.    What does the typedef keyword do?
6.    What is the difference between constants defined through #define and the constant keyword?
7.    What are Trigraph characters?
8.    How are floating point numbers stored? Whats the IEEE format?
9.    When should a type cast be used?
10. Can structures be assigned to variables and passed to and from functions?

 

No comments:

Post a Comment