For working professionals
For fresh graduates
More
Explore C Tutorials: From Begi…
1. Introduction to C Tutorial
2. Addition of Two Numbers in C
3. Anagram Program in C
4. Armstrong Number in C
5. Array in C
6. Array of Pointers in C
7. Array of Structure in C
8. C Program to Find ASCII Value of a Character
9. Assignment Operator in C
10. Binary Search in C
11. Binary to Decimal in C
12. Bitwise Operators in C
13. Boolean in C
14. C Compiler for Mac
15. C Compiler for Windows
16. C Function Call Stack
17. C Language Download
18. Operators in C
19. C/C++ Preprocessors
20. C Program for Bubble Sort
21. C Program for Factorial
22. C Program for Prime Numbers
23. C Program for String Palindrome
24. C Program to Reverse a Number
25. Reverse a String in C
26. C string declaration
27. String Input Output Functions in C
28. Calculator Program in C
29. Call by Value and Call by Reference in C
30. Ceil Function in C
31. Coding Vs. Programming
32. Command Line Arguments in C/C++
33. Comments in C
34. Compilation process in C
35. Conditional Statements in C
36. Conditional operator in the C
37. Constant Pointer in C
38. Constants in C
Now Reading
39. Dangling Pointer in C
40. Data Structures in C
41. Data Types in C
42. Debugging C Program
43. Convert Decimal to Binary in C
44. Define And include in C
45. Difference Between Arguments And Parameters
46. Difference Between Compiler and Interpreter
47. Difference Between If Else and Switch
48. Do While Loop In C
49. Double In C
50. Dynamic Array in C
51. Dynamic Memory Allocation in C
52. Enumeration (or enum) in C
53. Evaluation of Arithmetic Expression
54. Factorial of A Number in C
55. Features of C Language
56. Fibonacci Series Program in C Using Recursion
57. File Handling in C
58. For Loop in C
59. Format Specifiers in C
60. Functions in C
61. Function Pointer in C
62. goto statement in C
63. C Hello World Program
64. Header Files in C
65. Heap Sort in C Program
66. Hello World Program in C
67. History of C Language
68. How to compile a C program in Linux
69. How to Find a Leap Year Using C Programming
70. Identifiers in C
71. If Else Statement in C
72. If Statement in C
73. Implementation of Queue Using Linked List
74. Increment and decrement operators in c
75. Input and Output Functions in C
76. How To Install C Language In Mac
77. Jump Statements in C
78. Lcm of Two Numbers in C
79. Length of an Array in C
80. Library Function in C
81. Linked list in C
82. Logical Operators in C
83. Macros in C
84. Matrix multiplication in C
85. Nested if else statement in C
86. Nested Loop in C
87. One Dimensional Array in C
88. Operator Precedence and Associativity in C
89. Overflow And Underflow in C
90. Palindrome Program in C
91. Pattern Programs in C
92. Pointer to Pointer in C
93. Pointers in C: A Comprehensive Tutorial
94. Pre-increment And Post-increment
95. Prime Number Program in C
96. Program for Linear Search in C
97. Pseudo-Code In C
98. Random Access Files in C
99. Random Number Generator in C
100. Recursion in C
101. Relational Operators in C
102. Simple interest program in C
103. Square Root in C
104. Stack in C
105. Stack Using Linked List 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
112. String Comparison in C
113. String Functions in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
118. Structure of C Program
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
122. Toupper Function in C
123. Transpose of a Matrix in C
124. Two Dimensional Array in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
129. User Defined Functions in C
130. What is Variables in C
131. Is C language case sensitive
132. Fibonacci Series in C
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.