C Constants
A constant is a value which cannot be changed after it is set. We use constants for fixed values like pi or the number of days in a week.
Using the const keyword
#include <stdio.h>
int main(void) {
const float PI = 3.14159f;
float radius = 5;
printf("Area = %.2f\n", PI * radius * radius);
// PI = 3.14; <- this line would give a compile error
return 0;
}
Output:
Output of the above program is
Area = 78.54
Using #define
#define creates a symbolic constant. The preprocessor replaces its name with the value before compiling. There is no semicolon at the end.
#include <stdio.h>
#define MAX_STUDENTS 50
#define COLLEGE "ABC College"
int main(void) {
printf("%s has %d students\n", COLLEGE, MAX_STUDENTS);
return 0;
}
Output:
Output of the above program is
ABC College has 50 students
const vs #define
| Property | const | #define |
|---|---|---|
| Type | Has a data type | No type, simple text replace |
| Scope | Follows normal scope rules | From the line it is written |
| Memory | Takes memory like a variable | No memory used |
| Debugging | Visible in the debugger | Not visible |
Literal constants
| Kind | Example |
|---|---|
| Integer | 10, -5, 0x1F |
| Float | 3.14, 2.5e3 |
| Character | 'A', '\n' |
| String | "Hello" |
Note:
By habit, constant names are written in capital letters, like MAX_SIZE.
Next: C printf and scanf.
Congratulations! Chapter Finished. Learn more about the similar topics: