#define
- C course
- Beginner
- Lesson 106/116
- 4 min
Learn to define constants and macros with #define.
#define: defining constants and macros
The #define preprocessor directive gives a name to a value. Before compilation, the preprocessor replaces the name with the value.
#define PI 3.14
#define MAX_USERS 10
printf("%.2f", PI); /* 3.14 */Here PI and MAX_USERS are constants; their names are used throughout the code, and they turn into their values before compilation. This is the standard way to name magic numbers. Since the value has no type, the compiler does not check it; use carefully.
Avoiding magic numbers with constants
Using named constants with #define instead of meaningless numbers makes code more readable.
#define BUFFER_SIZE 256
char buf[BUFFER_SIZE];
fgets(buf, BUFFER_SIZE, stdin);Here the number 256 appears twice; but since it is named BUFFER_SIZE, changing it is done in one place. The meaning of the number is also clear from its name. This approach is very valuable especially for repeated values.
Practice Define PI and print it
Define a constant with #define PI 3.14. In main print the value of PI with printf using the %.2f format.
Starter code
#include <stdio.h>
// Define a constant named PI (3.14)
int main(void) {
// Print the PI value with printf
return 0;
}Sample solution
#define PI 3.14
printf("%.2f\n", PI);Expected output
3.14
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does #define do?
- Declares a function
- Declares a variable
- Defines constants and macros Correct answer
- Defines a type
Explanation: #define defines constants and macros; replaced before compilation.
2 Fill in the blank: #define constant
____ PI 3.14
#define PI 3.14
Explanation: #define PI 3.14 defines a constant.
3 Match directive to task
| Term | Meaning |
|---|---|
#define |
Defines a constant |
#include |
Includes a header |
#ifdef |
Conditional compilation |
#endif |
Ends a block |