For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
In C, constants are values that remain unchanged throughout program execution. For example, the value of PI (3.14159) is constant in mathematical calculations.
These values represent data that remains constant, such as mathematical constants or predefined settings.
In this guide, you’ll explore the various types of constants in C with examples, focusing on how each type can be utilized in real-world scenarios. By the end of this, you’ll be able to write clean and efficient code.
Let’s dive into the details!
Boost your C programming skills with our Software Development courses — take the next step in your learning journey!
In C programming, constants are defined values that remain unchanged throughout the program.
There are two primary ways to define constants: using the const keyword and the #define preprocessor directive.
const is ideal for type-safe, modifiable constants at runtime, while #define is better for preprocessor-based, non-type-safe constants used at compile-time.
Let's explore both methods in detail.
The const keyword is used to define a constant variable. When you define a constant using const, the value of the constant cannot be altered throughout the program.
The syntax is simple and helps define constant variables with a specific data type.
#include <stdio.h>
int main() {
const int maxUsers = 100; // Define a constant using 'const'
printf("The maximum number of users is: %d\n", maxUsers);
// maxUsers = 200; // Uncommenting this will cause a compile-time error
return 0;
}
Output:
The maximum number of users is: 100
Explanation:
The #define preprocessor directive allows you to define constants without specifying a data type. This method simply replaces all instances of the constant with the value during the preprocessing stage, before compilation.
It’s commonly used for defining constant values such as mathematical constants, configuration values, or flags.
#include <stdio.h>
#define MAX_USERS 100 // Define a constant using '#define'
int main() {
printf("The maximum number of users is: %d\n", MAX_USERS);
// MAX_USERS = 200; // Uncommenting this will cause a compile-time error
return 0;
}
Output:
The maximum number of users is: 100
Explanation:
On that note, let's move forward and explore the types of constants in C with examples.
Constants in C come in various forms, each serving a different purpose. Below, we'll go over each of the constant types, their declaration rules, and examples for better understanding.
An integer constant is a constant that represents whole numbers. It can be positive, negative, or zero.
Rules:
Syntax:
#include <stdio.h>
int main() {
const int num = 42;
printf("Integer constant: %d\n", num);
return 0;
}
Output:
Integer constant: 42
A character constant represents a single character enclosed in single quotes.
Rules:
Syntax:
#include <stdio.h>
int main() {
const char letter = 'A';
printf("Character constant: %c\n", letter);
return 0;
}
Output:
Character constant: A
A floating-point constant represents numbers with fractional values. It is typically used for decimal points.
Rules:
Syntax:
#include <stdio.h>
int main() {
const float pi = 3.14f;
printf("Floating-point constant: %.2f\n", pi);
return 0;
}
Output:
Floating-point constant: 3.14
This type of constant holds a larger precision value compared to the regular floating-point constant.
Rules:
Syntax:
#include <stdio.h>
int main() {
const double pi = 3.14159265359;
printf("Double precision constant: %.12f\n", pi);
return 0;
}
Output:
Double precision constant: 3.141592653590
An array constant in C is an array whose elements are predefined and cannot be modified after initialization.
Typically declared using the const keyword, it stores multiple constants of the same type, ensuring that the values remain fixed throughout the program.
Rules:
Syntax:
#include <stdio.h>
int main() {
const int arr[] = {1, 2, 3, 4};
printf("Array constant: %d, %d\n", arr[0], arr[1]);
return 0;
}
Output:
Array constant: 1, 2
Also Read: What is Array in C? With Examples
A structure constant represents a structured collection of different data types.
Rules:
Syntax:
#include <stdio.h>
struct Person {
const char name[30];
const int age;
};
int main() {
const struct Person person1 = {"Parth", 45};
printf("Structure constant: Name: %s, Age: %d\n", person1.name, person1.age);
return 0;
}
Output:
Structure constant: Name: Parth, Age: 45
Also Read: Data Types in C and C++ Explained for Beginners
Now that you understand the types of constants, let's explore how they differ from literals.
In C programming, a literal refers to a constant value that appears directly in the source code. For example, when you write int x = 10;, the number 10 is a literal.
Literals are directly used in expressions or assigned to variables, and they don’t require any additional declaration.
While constants and literals might seem similar at first glance, understanding their distinctions will help you use them effectively.
The table below outlines these differences:
Aspect | Constant | Literal |
Definition | A fixed value that is declared and cannot be modified after initialization. | A value that directly appears in the code without being assigned to a variable. |
Memory Allocation | Constants are stored in memory with a specific name. | Literals are not stored; they are used directly in expressions. |
Declaration | Constants are declared using const or #define. | Literals are written directly in the code without any declaration. |
Use | Constants can be used like variables but cannot change their value. | Literals are used directly in code and cannot be modified. |
Example | const int MAX_SIZE = 100; | printf("%d", 5); |
Next, let's explore what happens when you attempt to change the value of a constant.
Constants in C are immutable values that remain unchanged throughout the program's execution.
What Happens If You Try to Change a Constant:
Trying to change a constant’s value results in a compile-time error to maintain its integrity.
For example, if you try to reassign a value to a constant like this:
const int maxValue = 100;
maxValue = 200; // Error: Cannot change the value of a constant
You will get an error message from the compiler, such as:
error: assignment of read-only variable 'maxValue'
This error prevents unexpected changes, ensuring program stability.
This quiz will test your knowledge of constants in C programming. From the basics to more complex concepts, let's see how well you truly understand the use and applications of constants in C!
1. Which of the following is the correct way to define a constant in C?
A) constant int x = 10;
B) const int x = 10;
C) int const x = 10;
D) x = 10; const int
2. What will happen if you attempt to modify the value of a constant variable in C?
A) The program will print an error message
B) The program will compile, but the value won't change
C) The program will result in a runtime error
D) The compiler will generate an error message
3. Which of the following keywords is used to define a constant in C?
A) fixed
B) constant
C) const
D) static
4. What is the scope of a constant defined using the #define directive in C?
A) It is local to the function where it is defined
B) It is global to the entire program
C) It is only available in header files
D) It is available only within the file it is defined in
5. What is the output of the following code snippet?
#define PI 3.14
int main() {
printf("%f", PI);
return 0;
}
A) It will print 3.14
B) It will print an error
C) It will print PI
D) It will print 0
6. Which of the following defines a constant that can be used in all files included in a C project?
A) const
B) #define
C) static const
D) extern const
7. What is the main difference between const and #define in C?
A) const is a keyword, while #define is a preprocessor directive
B) const can be used for variables, but #define cannot
C) #define creates variables, while const does not
D) There is no difference; they function the same
8. How can constants improve the maintainability of C code?
A) By improving runtime performance
B) By making the code more readable and easier to update
C) By increasing memory usage
D) By removing the need for loops
9. What is the purpose of the const keyword when used in function parameters?
A) It prevents the function from returning a value
B) It ensures the function doesn't modify the value of the passed parameter
C) It makes the function parameter static
D) It allows the parameter to be shared across multiple functions
10. Can a constant pointer to a variable be declared in C?
A) No, pointers cannot be constants
B) Yes, by using const int* ptr = &x;
C) Yes, but only with #define
D) Yes, by using int* const ptr = &x;
Understanding constants is just the beginning—keep building your C programming skills with expert-led courses and hands-on learning.
upGrad offers structured courses that will help you master the concepts of constants and other essential elements of C programming. From using const to working with #define directives, these courses will equip you with the skills needed for efficient C programming, optimizing both your problem-solving abilities and your coding expertise.
Explore upGrad’s in-depth courses to sharpen your C programming skills:
You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!
Similar Reads:
Explore C Tutorials: From Beginner Concepts to Advanced Techniques
Addition of Two Numbers in C: A Comprehensive Guide to C Programming
C Program to check Armstrong Number
Find Out About Data Structures in C and How to Use Them?
C Program to Convert Decimal to Binary
The types of constants in C include integer constants, character constants, floating-point constants, and string constants, each with distinct syntax and rules.
You can define constants in C using the const keyword or the #define preprocessor directive, depending on your needs.
The const keyword creates typed constants that the compiler enforces, while #define is a preprocessor macro, not checked by the compiler.
No, constants in C are immutable. Attempting to modify them results in a compile-time error, maintaining data integrity.
The const keyword ensures that once a constant is defined, its value cannot be modified. Example: const int maxValue = 100;.
Constants in C are often placed in read-only memory segments to prevent modification, helping optimize memory usage and ensuring data integrity.
String constants in C are defined by enclosing a sequence of characters in double quotes. Example: const char* str = "Hello";.
Constants provide safety and clarity in programs by ensuring values remain unchanged, preventing bugs caused by accidental value changes.
Yes, #define can be used for any constant, including string and character constants, in C programming.
Yes, constants in C are generally more efficient as they are optimized by the compiler and prevent unnecessary memory allocation or re-assignment.
Constants help in optimizing the code by ensuring that fixed values are stored efficiently and avoid unnecessary memory usage during execution.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.