www.thecareerplus.com
The CareerPlus
Home Technical Resources Programming Variables and Data types
Wednesday 08th September 2010
 
 
What is the difference between constants defined through #define and the constant keyword?

Discuss it!          


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.

Discuss it!          

CrackTheIntervew.NET
Advertisement
 
Top! Top!