In this lesson, you will learn about Constants in C, and their usages, along with examples to better understand the topic.
As the name indicates, a constant is an identifier that, once defined, cannot modify through the program’s execution. Constant has some properties like it is case-sensitive, always uppercase, and cannot be undefined. By convention, the constant’s name begins with a letter or underscore, followed by any numbers, underscores, or letters. Constants have, by default, global scope throughout the whole program.
const double PI = 3.14;
// Example of constant statement #include <stdio.h> int main () { const int var = 2050; printf ("Constant value %d\n", var); return 0; }
Output
Constant value 2050
Once a constant is declared and assigned a value, it cannot be changed. In the example below, the program will throw an error as, later in the program, you try to change its value.
// Example of constant statement #include <stdio.h> int main () { const int var = 2050; var = 2060; printf ("Constant value %d\n", var); return 0; }
Output
error: assignment of read-only variable ‘var’
In the next lesson, you will learn about the different Data Types available in the C Programming Language.