- What is Constant in C?
- How to Declare a Constant in C?
- Using #define Preprocessor Directive to Define Constant in C
- Defining Constant in C Using the const Keyword
- Rules for Defining a Constant in C
- Types of Constants in C
- Importance of Constants in C
- Changing the Value of const in C (Pointers Section)
- Conclusion
- Frequently Asked Questions
Constant In C | How To Define, Rules & Types (+Detailed Examples)
In C programming, a constant is a value that does not change during the execution of a program. In simple terms, constants in C language are variables whose values are set once and cannot be altered while the program runs. These can be of various types, such as integer constants, character constants, floating-point constants, and more.
For example, if you’re writing a program that uses the value of Pi (3.14) multiple times, defining it as a constant ensures the value stays consistent throughout the code.
In this article, we’ll cover everything about constants in C programming—what they are, how to declare them using const and #define, the types of constants, their rules, and more—with practical examples and clear explanations. Let’s get started!
What is Constant in C?
A constant in C refers to a variable whose value remains fixed throughout the lifecycle of a program. Once assigned, the value of a constant cannot be modified, which helps prevent unexpected changes and reduces potential bugs.
Constants are usually declared at the beginning of the program and are used wherever that fixed value is needed. This not only prevents accidental changes but also makes your code cleaner, easier to update, and more maintainable. C language provides two primary ways to define constants—the use of the const keyword and the #define preprocessor directive.
Using constants improves the readability and reusability of code. It also follows the best practice of avoiding "magic numbers"—hard-coded values with no explanation—scattered throughout the code.
Look at the simple C program example below, which illustrates these rules. In the sections ahead, we will discuss the methods of constant variable definition in detail.
Code Example:
#include
const int MAX_VALUE = 100;
const float PI = 3.14;
int main() {
const int MIN_VALUE = 0;
printf("Max value: %d\n", MAX_VALUE);
printf("Pi: %.2f\n", PI);
printf("Min value: %d\n", MIN_VALUE);
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+Cgpjb25zdCBpbnQgTUFYX1ZBTFVFID0gMTAwOwpjb25zdCBmbG9hdCBQSSA9IDMuMTQ7CgppbnQgbWFpbigpIHsKY29uc3QgaW50IE1JTl9WQUxVRSA9IDA7CgpwcmludGYoIk1heCB2YWx1ZTogJWRcbiIsIE1BWF9WQUxVRSk7CnByaW50ZigiUGk6ICUuMmZcbiIsIFBJKTsKcHJpbnRmKCJNaW4gdmFsdWU6ICVkXG4iLCBNSU5fVkFMVUUpOwoKcmV0dXJuIDA7Cn0=
Output:
Max value: 100
Pi: 3.14
Min value: 0
Explanation:
We begin the example by including the header file <stdio.h> for input/output operation.
- Then, we declare and initialize two constant variables, MAX_VALUE (of integer type)and PI (of float type), with the values 100 and 3.14, respectively.
- Note that these are global constants since they are declared before the main() function.
- Inside the main() function, we declare another local integer type constant, MIN_VALUE, with the initial value 0.
- Next, we use a set of printf() statements to access and display all the values to the console.
- As shown in the output:
- Constant variables defined outside main() have a global scope or are accessible globally from anywhere in the program.
- Constant declared inside main() has a local scope, i.e., it can only be accessed from within main (local access).
- All constants maintain their assigned values throughout the execution.
This simple C code example captures the essence of a constant in C—they're declared once and provide stability and clarity by ensuring values don't change unexpectedly.
How to Declare a Constant in C?
Declaring constants in C programs is a crucial step when you want to ensure certain values remain unchanged throughout your program. Instead of hardcoding values repeatedly, constants offer a clean, reusable, and error-free way to manage fixed data.
In C, constants can be defined using two primary methods:
- Using the const keyword: This is a type-safe way to declare constants that are bound to a specific data type (e.g., const int, const float).
- Using the #define preprocessor directive: This method defines symbolic constants (macros) and is processed before compilation.
In the next sections, we’ll explore each of these methods in detail with examples.
Using #define Preprocessor Directive to Define Constant in C
The #define directive is a preprocessor command used to create symbolic constants or macros in C. It replaces specified tokens in your source code with defined values before the compilation process begins. This is especially useful for defining values that remain unchanged throughout the program.
Syntax of #define constant in C:
#define CONSTANT_NAME constant_value
Here:
- CONSTANT_NAME: The name or identifier for the constant (by convention, written in all uppercase).
- constant_value: The value that will replace the identifier wherever it appears in the code.
This method improves code readability and reduces repetition, making it easier to manage fixed values across your program.
Examples of Defining Constants in C Using #define:
#define BUFFER_SIZE 1024
#define PI 3.14159
After defining PI, every occurrence of PI in the code is automatically replaced with 3.14159 during preprocessing.
The #define directive is particularly effective when you want to:
- Apply a constant across multiple functions.
- Avoid type declarations (though this can also be a limitation in some cases).
- Improve code portability and consistency.
Look at the C program example below for the implementation of this method of defining a constant.
Code Example:
#include
#define PI 3.14159
int main() {
printf("%f", PI);
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNkZWZpbmUgUEkgMy4xNDE1OQoKaW50IG1haW4oKSB7CiAgICBwcmludGYoIiVmIiwgUEkpOwogICAgcmV0dXJuIDA7Cn0=
Output:
3.14159
Explanation:
In this C code example:
- We use the #define preprocessor directive to create a symbolic constant PI with a value of 3.14159.
- Inside the main() function, we use the printf() function with a formatted string to display the value of PI.
- Here, the %f format specifier is a placeholder for the floating point values.
- When the code is compiled, every instance of PI is replaced with 3.14159, ensuring consistency and preventing accidental modification.
✅ Tip: Use #define for constants that are global and not type-specific. For type-safe constants, the const keyword is more appropriate (covered in the next section).

Defining Constant in C Using the const Keyword
The const keyword—also known as the const qualifier—is a widely used method for defining constants in C. When used with a variable declaration, it tells the compiler that the value of a variable cannot be modified after initialization, offering a type-safe and more readable alternative to #define.
- In other words, the const keyword in C is a type-safe and compiler-enforced way to define constants that remain unchanged throughout the program.
- Unlike #define, it respects data types, allows scope control (local or global), and integrates seamlessly with debugging tools—making it ideal for safer and more maintainable code.
Syntax of Defining Constants Using const
const data_type constant_name = value;
Here:
- const: Declares that the variable is a constant.
- data_type: Specifies the type of value (e.g., int, float, char, etc.).
- constant_name: The identifier for the constant variable.
- value: The value assigned to the constant.
This method binds a fixed value to a variable, and any attempt to modify it will result in a compile-time error.
Examples of Defining Constant in C using const Keyword:
const int MAX_VALUE = 100;
Here, MAX_VALUE is a constant of type int set to 100. You cannot reassign it anywhere later in the program. Any attempt to modify it later in the program will result in a compilation error. Look at the example C program below for a better understanding of how this method is implemented.
Code Example:
#include
int main() {
// Declare a constant called MAX_VAL
const int MAX_VAL = 100;
// Printing the integer value of the constant variable
printf("The maximum value is: %d\n", MAX_VAL);
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CmludCBtYWluKCkgewogICAgLy8gRGVjbGFyZSBhIGNvbnN0YW50IGNhbGxlZCBNQVhfVkFMCiAgICBjb25zdCBpbnQgTUFYX1ZBTCA9IDEwMDsKICAgIC8vIFByaW50aW5nIHRoZSBpbnRlZ2VyIHZhbHVlIG9mIHRoZSBjb25zdGFudCB2YXJpYWJsZQogICAgcHJpbnRmKCJUaGUgbWF4aW11bSB2YWx1ZSBpczogJWRcbiIsIE1BWF9WQUwpOwogICAgcmV0dXJuIDA7Cn0K
Output:
The maximum value is: 100
Explanation:
In the example C code-
- We initiate the main() function, which is the entry point for the program's execution.
- Inside main(), we define a constant integer variable MAX_VAL using const keyword and assign the value 100 to it.
- Next, as mentioned in the code comments, we use the printf() library function to display the value of the variable with a descriptive string message.
- Here, we use the %d format specifier for integers and the newline escape sequence (\n), which shifts the cursor to the next line.
- Finally, the main() function completes with a return 0 statement, indicating successful execution.
Advantages of Using the const Keyword/Qualifier in C
- Prevents accidental changes: Attempting to modify a const variable leads to a compile-time error, preventing bugs before they occur.
- Improves code readability: Using a constant in C programs with descriptive names to replace hard-coded values (a.k.a. “magic numbers”) makes the code more understandable and maintainable.
Other Practical Uses of const in C
Here are some other ways in which we can use the const qualifier in C programs:
1. Fixed Array Size Definition
const int ARRAY_SIZE = 10;
int myArray[ARRAY_SIZE];
Here, we first define a constant variable to hold the size of an array. Then, when defining the array, we can use this const value to represent the size. This approach ensures the array size stays consistent and readable.
2. Mathematical Constant Definition
const double PI = 3.14159265359;
Used for fixed mathematical values that must not change.
3. Boolean Flags Creation
const int TRUE = 1;
const int FALSE = 0;
Boolean values are often used in control statements and comparative operations. It is important for these values to remain constant throughout, i.e., immutable.
Check out this amazing course to become the best version of the C programmer you can be.
Rules for Defining a Constant in C
In C, constants are used to define values that should not change during program execution. You can define constants using either the const keyword or the #define preprocessor directive. However, a few rules must be followed to ensure proper usage and definition of constant in C:
1. Using the const Keyword
When using const, the syntax is:
const data_type variable_name = value;
- The const keyword is placed before the data type of the value.
- The value must be assigned at the time of declaration itself.
- Once defined, the value cannot be modified.
2. Using the #define Preprocessor Directive
An alternative and common way to define constants is using the #define directive, which creates symbolic constants. Unlike const, this method does not involve a data type. Example:
#define PI 3.1415
- PI is replaced by 3.1415 throughout the code during preprocessing.
- No equal sign (=) or semicolon is used.
- This method is often preferred for defining global constants or configuration values.
3. Scope of Constants
- const constants follow normal variable scoping rules. If defined within a function, they are local to that function. If defined outside any function, they are global.
- #define constants are generally global and accessible across the program unless restricted with conditional compilation.
4. Immutability
Once a constant is defined—whether using const or #define—its value cannot be modified. Any reassignment attempt will cause a compile-time error (for const) or unintended behavior (for #define).

Types of Constants in C
In C programming, constants are broadly classified into two categories:
- Primary Constants: These include character constants, real (floating-point) constants, and integer constants.
- Secondary Constants: These include arrays, pointers, structures, unions, and enumerations (enum).
Table of Primary Constant in C (+Examples)
|
Type Of Constants |
Data Type |
Examples |
|
Integer Constants (int) |
unsigned int |
200u, 500U |
|
long int, long long int |
10, -5, 0 |
|
|
Floating-point or Real Constants |
float, double |
10.584634, 3.14 |
|
Character Constants |
char |
'X', 'Y', 'Z' |
The table provides a quick overview of the different types of constants in C. We will discuss these in detail in the following sections.
Primary Constants in C
Primary constants are literal values that belong to standard data types and are written directly in the code. They are not subject to substitution or further operations. In other words, primary constants in C are those that are of the standard data type. For example:
- Integer: 3, 10
- Floating-point: 2.33, 3.14
- Character: 'h', "Hello"
Primary constants in C can further be divided into standard types, i.e., integer, floating-point, and character constants. An explanation for all is given ahead.
Integer Constant in C
Numeric constants that represent whole numbers are referred to as integer constants in C. They can be written in many formats, including decimal, binary, octal, and hexadecimal. Here are some examples:
- Decimal Format: 42, 100
- Octal Format: 052 (equivalent to decimal 42)
- Hexadecimal Format: 0xFF (equivalent to decimal 255)
- Binary format (C99 and above): 0b101010 (equivalent to 42)
You can also suffix letters infront of these constants to indicate their type. For example, integer constants ending in U represent unsigned integers, and constants ending in L represent long integers. Some examples of integer constants in C with suffixes are:
- Unsigned Integer: 42U
- Long Integer: 123456L
- Unsigned Long Integer: 0xFFUL
Floating-Point Constant In C (Real Constants)
Constants that represent real numbers and support are known as floating point constants in C. They can be written in two forms: decimal and exponential. Some examples of floating point in C are:
- Decimal Format: 3.14, 0.123, 1000.
- Exponential Notation/ Format: 3.14e2 (equal to 314), 1.23e-3 (equal to 0.00123)
In exponential form, the letters e or E indicate that the value is multiplied by the power of 10. For example, 3.14e2 means that 3.14 is raised to the power (10*2), which equals 314.
Character Constants In C
A constant character represents a single character enclosed in single quotes (' '). They can represent alphanumeric and special characters. Some examples of character constants in C are:
- 'A' (represents the character 'A')
- 'a' (represents the character 'a')
- '3' (represents the character '3')
- ' ' (represents a whitespace character/ space)
- '\n' (represents a newline character/ escape sequence)
- ''' (represents a single quote character)
- '\' (represents a backslash symbol/ character)
String Constants In C
They represent a sequence of characters enclosed in double quotes (" "). It can also contain text, including alphanumeric characters and other special characters. Some examples of string constants in C are:
- "Hello, world!" (represents the string "Hello, world!")
- "12345" (represents the string "12345")
- " " (represents a string with a single whitespace character)
- "A\nB" (represents the string "A" followed by a newline character and then "B")
Each string ends with a null character ('\0') automatically added by the compiler. For example, "Hello" is stored as {'H', 'e', 'l', 'l', 'o', '\0'}.
Backslash Character Constants In C
The backslash (\) is used to create escape sequences and helps represent a special character that cannot be typed directly into a string. For example, characters like single and double quotes have predefined meanings in programming language as they are used in character and string creation.
|
Meaning of Character |
Backslash Character |
|
Backspace |
\b |
|
New line |
\n |
|
Form feed |
\f |
|
Horizontal tab |
\t |
|
Carriage return |
\r |
|
Single quote |
\’ |
|
Double quote |
\” |
|
Vertical tab |
\v |
|
Backslash |
\\ |
|
Question mark |
\? |
Hone your coding skills with the 100-Day Coding Sprint at Unstop and claim bragging rights now!
Importance of Constants in C
Constants play a crucial role in writing clean, maintainable, and bug-free C programs. Instead of hardcoding values throughout your code, constants allow you to define meaningful names for fixed values—improving readability, reducing errors, and making future updates much easier.
Here are some common use cases and reasons why constants are important:
1. Improve Code Readability
Using constants makes your code easier to understand at a glance. Instead of:
if (score > 40) ...
You can write:
const int PASS_MARK = 40;
if (score > PASS_MARK) ...
This gives immediate context to what 40 represents without needing comments.
2. Avoid Magic Numbers
"Magic numbers" are unnamed numeric constants that appear in code without explanation. Constants help eliminate them, making your logic self-explanatory and less error-prone.
3. Ease of Maintenance
When a constant value needs to change, you can update it in just one place, rather than hunting through the entire codebase. For example:
#define MAX_USERS 100
If the limit increases, you only update the value of MAX_USERS.
4. Enforce Immutability
Constants protect values from being accidentally modified. This is especially useful in large projects or collaborative environments where such errors are more likely to occur.
5. Enhance Debugging and Testing
Well-named constants make debugging easier. When issues arise, you can clearly identify what each value is supposed to represent, without second-guessing its intent.
6. Enable Reusability
Constants can be reused across multiple functions or modules—especially when declared globally—ensuring consistency throughout the program.
7. Support Platform-Dependent Code
You can define constants conditionally for different environments or systems using #define along with #ifdef, making your program more portable and adaptable.
Changing the Value of const in C (Pointers Section)
In C, variables declared with the const keyword are meant to be read-only—you cannot (and should not) modify their value directly after initialization. However, when pointers come into play, things get a bit nuanced.
Let’s understand how const behaves when used with pointers and whether it’s possible (or safe) to change the value of a const variable through them.
Can You Change the Value of a const Variable?
Directly, no. The compiler will throw an error if you try:
const int num = 10;
num = 20; // ❌ Error: assignment of read-only variable
However, indirect modification is possible through pointer manipulation—though it's not recommended as it breaks the purpose of using const.
Example: Modifying a const Variable via Pointers
#include
int main() {
const int value = 10;
int *ptr = (int*)&value; // casting away const-ness
*ptr = 20; // modifying the value
printf("Modified value: %d\n", value);
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CmludCBtYWluKCkgewogICAgY29uc3QgaW50IHZhbHVlID0gMTA7CiAgICBpbnQgKnB0ciA9IChpbnQqKSZ2YWx1ZTsgIC8vIGNhc3RpbmcgYXdheSBjb25zdC1uZXNzCiAgICAqcHRyID0gMjA7ICAgICAgICAgICAgICAgIC8vIG1vZGlmeWluZyB0aGUgdmFsdWUKICAgIHByaW50ZigiTW9kaWZpZWQgdmFsdWU6ICVkXG4iLCB2YWx1ZSk7CiAgICByZXR1cm4gMDsKfQ==
Output (may vary):
Modified value: 20
⚠️ Warning:
This technique works by typecasting and effectively bypassing the const protection. However, doing so causes undefined behavior—which means the outcome is unpredictable, and the program might crash or behave incorrectly depending on the compiler and platform.
Pointers and const: Different Combinations
The keyword const can be applied to either the data being pointed to, the pointer itself, or both. Here are the variations:
|
Declaration |
Meaning |
|
const int *ptr |
Pointer to a const int (you cannot modify the value) |
|
int *const ptr |
Constant pointer to an int (you cannot change the pointer address) |
|
const int *const ptr |
Constant pointer to a constant integer (neither the value nor address can be changed) |
Why This Matters: Understanding how const interacts with pointers helps you write safer, more predictable C programs. It also reinforces one of C’s core philosophies: just because something is possible doesn’t mean it’s safe or portable.
Conclusion
Constants in C language are used to define values that remain unchanged during the execution of a program. There are two ways of creating constants: using the const qualifier/ keyword or using the #define preprocessor directive. They can be created globally for access throughout the program or locally in which case they can be accessed only within the block they are defined in.
They enhance code readability, prevent accidental changes to important values, and are crucial for defining fixed values, such as array dimensions, flags, macros, and mathematical constants. Additionally, constants in C programs enhance stability by enabling the safer passing of parameters to functions and reliable variable initialization. Constants play a significant role in structuring robust and error-free code, helping maintain program integrity and making the code more readable.
Also Read: 100+ Top C Interview Questions With Answers (2024)
Frequently Asked Questions
Q. What is the difference between a variable and a constant in C?
|
Aspect |
Variable |
Constant |
|
Mutability |
Can change during execution |
Cannot change after initialization |
|
Declaration |
int age = 25; |
const int AGE = 25; |
|
Usage |
Used when values are expected to vary |
Used when values must remain fixed |
|
Modification |
Allowed |
Not allowed (compiler error) |
Q. What is the difference between a const and a literal in C?
|
Aspect |
const |
Literal |
|
Definition |
A named variable marked unchangeable |
A hardcoded fixed value |
|
Example |
const int x = 10; |
10, 'A', "hello" |
|
Memory |
Stored in a named memory location |
Embedded directly in code |
|
Purpose |
Improves readability and reusability |
Represents exact value as-is |
Q. What is the difference between #define and const in C?
|
Aspect |
#define Macro |
const Keyword |
|
Syntax |
#define PI 3.14 |
const float PI = 3.14; |
|
Type checking |
No type checking |
Enforces type safety |
|
Scope |
Global (unless undefined) |
Follows variable scoping rules |
|
Debugging |
Difficult (no variable name in symbol table) |
Easier (exists in symbol table) |
|
Use Case |
Constants for compile-time replacement |
Typed constants for safer code |
Q. Is there any difference between floating-point constants and real constants?
Floating point constants represent real numbers with fractional parts. They are stored in computer memory using a format that allows for a certain degree of perfection and variety (precision). Floating point constants are frequently used in applications requiring exact/ precise calculations, such as scientific or engineering computations.
Real constants represent real numbers, often stored as floating-point values in many programming languages. However, different languages may store them in various formats (including but not limited to floating-point value format), depending on their required precision or range.
Q. What are the types of constants in C?
Constants in C are classified based on their data types and usage. Major types include:
- Integer constants: 10, -5, 0xFF
- Floating-point constants: 3.14, 2.5e3
- Character constants: 'a', '3', '\n'
- String constants: "Hello", "123"
- Enumeration constants: enum Color { RED, GREEN };
- Hexadecimal constants: 0x1A, 0xFF
- Boolean constants (C99+): _Bool is_valid = 1;
Q. What is the use of the const keyword?
The const keyword in C is used to declare a variable as a constant. This helps ensure that once initialized, these values cannot be modified/ changed. This is useful when you want to ensure that the value of a variable remains constant throughout the program and cannot be accidentally modified.
Example: const int MAX_VALUE = 100;
Q. Is there any way to change the value of a constant variable in C?
The whole purpose of defining variable constants in C programs is to avoid accidental or any changes to the value once initialized. There is one way to alter these values, but it is not recommended that you do so. To change the value of a constant variable, you can use a pointer to directly modify the memory address where the constant is stored. This bypasses the protection offered by the const keyword.
const int MAX_VALUE = 100;
int *ptr = (int *)&MAX_VALUE; // Use a pointer to change the value
*ptr = 200;
printf("%d", MAX_VALUE); // Output: 200
In the code snippet above, we have a const int MAX_VALUE whose address we assign to the pointer variable ptr. Here, we typecast the pointer type from const int to int. After that, we change the value pointed to by ptr to 200, thus modifying the value stored in the MAX_VALUE variable. Note that this approach is considered bad practice and should be avoided, as it undermines the intention behind declaring a variable as const.
This compiles our discussion on constant in C. Go ahead and explore the following topics:
- Typedef In C | Syntax & Use With All Data Types (+ Code Examples)
- Bitwise Operators In C Programming Explained With Code Examples
- Understanding Looping Statements In C [With Examples]
- Conditional/ If-Else Statements In C Explained With Code Examples
- Difference Between Call By Value And Call By Reference (+Examples)
An economics graduate with a passion for storytelling, I thrive on crafting content that blends creativity with technical insight. At Unstop, I create in-depth, SEO-driven content that simplifies complex tech topics and covers a wide array of subjects, all designed to inform, engage, and inspire our readers. My goal is to empower others to truly #BeUnstoppable through content that resonates. When I’m not writing, you’ll find me immersed in art, food, or lost in a good book—constantly drawing inspiration from the world around me.
Login to continue reading
And access exclusive content, personalized recommendations, and career-boosting opportunities.
Subscribe
to our newsletter
Comments
Add comment