← The C Language
Lesson 10 of 77 · 10 XP
Constants
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A value that must not change is declared with const:
const double PI = 3.14159;
PI = 3; // a compile error — and that's a good thing
The second, older way is a preprocessor macro:
#define MAX_PLAYERS 4
The preprocessor is a first pass before compilation: it literally replaces the text MAX_PLAYERS with 4 throughout the file. A macro has no type and isn't visible in the debugger, but it can be used where a compile-time constant is needed, for example as an array size.
Literals have types too:
42 // int
42u // unsigned int
42LL // long long
3.14 // double
3.14f // float
'A' // a character (an int in C)
"text" // a string
0x1F // hexadecimal = 31
0755 // OCTAL = 493! A leading zero changes the number base
Constants are customarily named in CAPITAL_LETTERS.
Task. Declare a constant SECONDS_PER_DAY (with #define or const), read a number of days and print how many seconds that is.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.