About Me

My photo
Bangalore, Karnantaka, India
Hi Frndss... I am Divya Prakash, presently working as an ABAP consultant , simplicity is my Prime Importance n I beleive in " First Deserve then DESIRE ".

Tuesday, October 27, 2009

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.
Hope this was useful....:)
- - - Div

No comments:

Pic :)

Pic :)
Look at !!!