Constants in C
Our program demonstrates the use of constants in C. Here’s the full source code:
#include <stdio.h>
#include <math.h>
#define S "constant"
#define N 500000000
int main() {
printf("%s\n", S);
const int n = N;
// Constant expressions perform arithmetic with precision
const double d = 3e20 / n;
printf("%e\n", d);
// In C, constants are typically of a specific type
printf("%lld\n", (long long)d);
// math.h functions expect double by default
printf("%f\n", sin(n));
return 0;
}
In C, we use #define
to declare symbolic constants and const
to declare constant variables.
The #define
directive is used to create a symbolic constant S
with the value “constant”.
#define S "constant"
A const
variable can be declared anywhere a regular variable can be declared.
const int n = N;
Constant expressions perform arithmetic with the precision of the types involved.
const double d = 3e20 / n;
printf("%e\n", d);
In C, constants typically have a specific type. When needed, we can use explicit type casting.
printf("%lld\n", (long long)d);
Functions from math.h
, like sin()
, expect double
arguments by default.
printf("%f\n", sin(n));
To compile and run this program:
$ gcc -o constants constants.c -lm
$ ./constants
constant
6.000000e+11
600000000000
-0.284704
Note that we need to link the math library (-lm
) when compiling.
C constants provide a way to define values that don’t change throughout the program, improving readability and maintainability.