C Constants
C constants are values that cannot change while the program runs. Using constants instead of repeating "magic numbers" makes code easier to read and to update.
The const Keyword
Put const before the type to make a variable read-only. It must be given its value when declared.
#include <stdio.h>
int main(void) {
const double PI = 3.14159;
double r = 2.0;
printf("Area: %.2f\n", PI * r * r);
// PI = 3.0; // error: assignment of read-only variable
return 0;
}Area: 12.57
Using #define
#define creates a preprocessor macro. Before compiling, every occurrence of the name is replaced by the text. Macros have no type and no semicolon.
#include <stdio.h>
#define MAX_USERS 50
#define GREETING "Welcome!"
int main(void) {
printf("%s Up to %d users.\n", GREETING, MAX_USERS);
return 0;
}Welcome! Up to 50 users.
#define vs const in C
- const variables have a type, so the compiler can check how they are used.
- const variables are visible in a debugger; macros disappear before compiling.
- #define values can be used where C requires a compile-time constant, such as some array sizes and case labels.
- Write constant names in UPPER_CASE by convention.
Literal Constants
Values written directly in code are literals: 42 (int), 42u (unsigned), 3.5 (double), 3.5f (float), 'x' (char), "text" (string), 0x1F (hexadecimal) and 017 (octal).
#include <stdio.h>
int main(void) {
printf("%d %d %d\n", 0x1F, 017, 42);
return 0;
}31 15 42
Frequently asked questions
What is the difference between #define and const in C?
#define is a text replacement done by the preprocessor and has no type. const creates a typed, read-only variable that the compiler checks. Prefer const for typed values and #define for compile-time constants and conditional compilation.
Can a const variable be changed in C?
Not through normal assignment; the compiler reports an error. Trying to change it through a pointer cast is undefined behavior.
Why are constants written in capital letters?
It is a naming convention that makes constants easy to spot. The compiler does not require it.