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.

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.

Advertisements

3 Responses to “What is the difference between constants defined through #define and the constant keyword?”

  1. Search Engine Optimization Says:

    Search Engine Optimization…

    […]What is the difference between constants defined through #define and the constant keyword? « TheWarrior[…]…

  2. cyber monday toshiba review Says:

    cyber monday toshiba review…

    […]What is the difference between constants defined through #define and the constant keyword? « TheWarrior[…]…

  3. Used Car Dealers Wellington Says:

    Used Car Dealers Wellington…

    […]What is the difference between constants defined through #define and the constant keyword? « TheWarrior[…]…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: