In many programs a #define
serves the same purpose as a constant. For example.
#define FIELD_WIDTH 10 const int fieldWidth = 10;
I commonly see the first form preferred over the other, relying on the pre-processor to handle what is basically an application decision. Is there a reason for this tradition?
The big advantage of const over #define is type checking. #defines can't be type checked, so this can cause problems when trying to determine the data type. If the variable is, instead, a constant then we can grab the type of the data that is stored in that constant variable.
#define is a preprocessor directive that is used to define macros in a C program. #define is also known as a macros directive. #define directive is used to declare some constant values or an expression with a name that can be used throughout our C program.
const and #define both are used for handle constants in source code, but they few differences. #define is used to define some values with a name (string), this defined string is known as Macro definition in C, C++ while const is a keyword or used to make the value of an identifier (that is constant) constant.
the benefit of using define is once you define the variable for exp: #define NUMBER 30, all the code in main will use that code with value 30. If you change the 30 to 40 it will directly change all value in main which using this variable (NUMBER).
There is a very solid reason for this: const
in C does not mean something is constant. It just means a variable is read-only.
In places where the compiler requires a true constant (such as for array sizes for non-VLA arrays), using a const
variable, such as fieldWidth
is just not possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With