A macro is a preprocessor directive that defines a constant value that can be used throughout the program. Macros are typically used to define constants that are used in multiple places in the code, and they can be defined using the #define
preprocessor directive. For example, the following code defines a macro named MAX_LEN
that represents the maximum length of a string:
#define MAX_LEN 100
Once a macro is defined, it can be used like any other constant in the program. For example, you can use the MAX_LEN
macro in an if
statement to check if a string is too long:
if (strlen(my_string) > MAX_LEN) { // string is too long }
A constant in C, on the other hand, is an object that cannot be modified once it has been assigned a value. Constants are typically declared using the const
keyword, like this:
const int MAX_LEN = 100;
In this example, the MAX_LEN
constant is declared as an int
type and initialized with the value 100
. Just like with a macro, the MAX_LEN
constant can be used in an if
statement to check if a string is too long:
if (strlen(my_string) > MAX_LEN) { // string is too long }
The main difference between a macro and a constant in C is that
a. Additionally, macros do not have any type checking, so you can use a macro to represent any type of value, while constants must be declared with a specific type.
- A macro is expanded by the preprocessor at compile time, while a constant is a real variable that exists at runtime. This means that a macro can be used to define values that are not known at compile time, such as the result of a complex expression, while a constant must be initialized with a fixed value.
- A macro do not have any type checking, so you can use a macro to represent any type of value, while constants must be declared with a specific type
- Inside code, we can never change the value of macro (because it was expanded and replaced at compile time) but a const variables value can be changes used a pointer. For example in below code we have declared a const int x with value 5 and then using a pointer we have changed its value to 10.
const int x = 5; int *ptr = &x; *ptr = 10; //value of x is now changed to 10 x = 20; //This can not be done and compiler will throw an error