In C, **Constants** (also known as literals) are fixed values that do not change during the execution of a program. Constants are used to represent values that are logically "read-only," such as the value of Pi, the number of days in a week, or a fixed tax rate. Using constants makes your code more secure and easier to maintain.
A constant is an identifier whose value is immutable. Unlike a standard variable, if you try to re-assign a new value to a constant after its definition, the C compiler will throw an error. This prevents accidental changes to critical data.
MAX_USERS is clearer than using a raw number like 100.There are two primary methods to define a constant in C. Each method has its own advantages depending on the scope and type of data.
The const keyword is the modern way to define a constant. It behaves like a variable but with a "read-only" restriction. It has a specific data type, which allows the compiler to perform type-checking.
The #define directive creates a "Macro." This is handled by the preprocessor before the actual compilation starts. It simply replaces every occurrence of the constant name with its value throughout the code.
Constants can represent different types of data, similar to variables. These are often called "Literals":
| Literal Type | Example | Description |
|---|---|---|
| Integer Literal | 45, -200 |
Whole numbers without any decimal point. |
| Floating-point | 3.14, 2.5e2 |
Real numbers with fractional parts or exponents. |
| Character Literal | 'Z', '7' |
Single characters enclosed in single quotes. |
| String Literal | "C Program" |
A sequence of characters in double quotes. |
For AdSense-quality documentation, it is important to understand which one to use and why:
const has a type (e.g., int), so the compiler can catch type-related bugs. #define has no type.const variables appear in the symbol table during debugging, making it easier to trace. #define names disappear after preprocessing.const can be limited to a specific function (local scope). #define is global for the entire file.While not a strict rule of the C language, it is a Standard Industry Practice to write constant names in all **UPPERCASE** letters with underscores for spaces. For example, use BUFFER_SIZE instead of bufferSize. This makes it instantly obvious to anyone reading your code that the value is a constant.
In this example, we use a constant for PI to calculate the circumference of a circle based on user-provided radius.
const, you must initialize it immediately. Writing const int x; x = 10; will result in an error because C considers the first line an attempt to create a "permanent" variable with a junk value.