What is the difference between the two?
The first is Macro , and the second is a variable declaration.
#define WIDTH 10
is a preprocessor directive that allows you to specify a name ( WIDTH
) and its replacement text ( 10
). The preprocessor parses the source file, and each occurrence of the name is replaced by the text associated with it. The compiler never sees the macro name at all, what it sees is replaced by text.
A variable declaration is evaluated by the compiler itself. It tells the compiler to declare a variable with the name WIDTH
and type int
, and also initializes it with a value of 10
.
The compiler knows this variable by its name WIDTH
.
Which one do you prefer? And why?
It is generally recommended to use compile-time variables compared to #define
. So your variable declaration should be:
const int width = 10;
There are several reasons for choosing compile time constants over #define
, namely:
Visibility Based Mechanism:
The scope of #define
limited by the file in which it is defined. Thus, #defines
that are created in one source file are NOT available in another source file. In short, #define
does not respect scope. Note that const
variables may be limited. They obey all the rules for determining the area.
Avoid weird magic numbers with compilation errors:
If you use #define
, they are replaced by the pre-processor during pre-compilation. So, if you get an error message at compile time, this will be confused because the error message will not refer to the macro name, but the value and it will display a sudden value, and everyone could spend a lot of time tracking this code .
Easy debugging:
Also for the same reasons stated in # 2, while debugging #define
will not provide any help.