In C programming, macros and constants are both used to represent fixed values, but they differ in how they work and how the compiler treats them.
Macros in C
In C programming, you can use macros to define constants or functions that you want to reuse in your program. Macros are part of the preprocessor directives. The preprocessor reads them and replaces the code before the compiler runs. To create a macro, use the #define directive.
Syntax for Macros:
#define MACRO_NAME value
Example of Macros:
#include <stdio.h> #define PI 3.14159 #define SQUARE(x) ((x) * (x)) int main() { // PI is replaced with 3.14159 printf("Area of circle: %.2f\n", PI * SQUARE(5)); return 0; }
- PI is a simple constant.
- SQUARE(x) is a function-like macro that calculates the square of a number.
Constants in C
Constants in C are values that do not change during the execution of a program. Once defined, their values remain fixed. Constants help make your code more readable, maintainable, and bug-free.
Syntax for Constants:
const data_type CONSTANT_NAME = value;
Example of Constants:
#include <stdio.h> int main() { const float PI = 3.14159; const int MAX_VALUE = 100; printf("Area of circle: %.2f\n", PI * 5 * 5); // Using constant PI return 0; }
PI is a constant that is treated like a variable but its value cannot be changed.
Difference Between Macros and Constants
Here are the main differences between Macros and Constants in C. This table shows how they are defined, how they work, and when to use them.
Feature | Macros | Constants |
---|---|---|
Definition | Defined using #define preprocessor directive | Defined using const keyword |
How It Works | Text is replaced before the code runs | Acts like a fixed variable in the code |
Type Checking | No type check; can be risky | Compiler checks the type |
Memory Use | Does not use memory | Uses memory like a variable |
Evaluation | Evaluated at the point of use (preprocessing) | Evaluated during runtime |
Debugging | Harder to debug due to preprocessor handling | Easier to debug as they behave like variables |
Side Effects | May cause problems if expressions are used | Safe and stable to use |
Best For | Simple text or math replacements | Values that should not change |
Function-Like Macros | Can simulate functions, accepting arguments | Cannot simulate functions |
Scope (Where It Works) | Works everywhere in the file | Works only in the defined block or file |
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Watch Advanced C Programming Videos
- Check C Books
- Practice Computer Science MCQs
- Check Computer Science Books
- Apply for Computer Science Internship