✏️ Explanatory Question

What is constant in C?

👁 805 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

What is a constant in C?

In C programming, a constant is a fixed value that does not change during the execution of a program. Constants are also commonly referred to as literals because they represent values that are directly written in the source code.

A constant can represent different types of values, such as an integer, floating-point number, character, or string. Constants are useful when a program needs to work with values that should remain unchanged throughout its execution.

Examples of Constants

100
3.14159
'A'
"Hello"

In the above examples, 100 is an integer constant, 3.14159 is a floating-point constant, 'A' is a character constant, and "Hello" is a string literal.

Using the const Keyword

In C, the const keyword can be used to declare an object whose value should not be modified through that identifier after initialization. For example:

const int MAX_MARKS = 100;

Here, MAX_MARKS is declared as a constant with an initial value of 100. Attempting to assign another value to it is not allowed:

MAX_MARKS = 200;   // Invalid

Constants Can Represent Different Data Types

C supports constants of different forms and data types. For example:

int age = 25;
float pi = 3.14159f;
char grade = 'A';

The values 25, 3.14159f, and 'A' are constants (more precisely, literals) used to initialize the variables.

Why Are Constants Used?

Constants make programs easier to understand and maintain. When a value represents an important fixed quantity, giving it a meaningful name makes the program more readable and reduces the chance of accidentally changing that value.

For example, instead of repeatedly using the value 3.14159, we can define:

const float PI = 3.14159f;

The identifier PI can then be used wherever the fixed value of pi is required.

Important Point

A const-qualified object in C should not be described as completely identical to a compile-time constant in every context. The const keyword mainly specifies that the object is not modifiable through that identifier. C also provides other forms of constants, such as integer constants, floating constants, character constants, enumeration constants, and string literals.

In Simple Terms

A constant is a fixed value used by a program that is not intended to be changed. Constants help make programs more readable, reliable, and easier to maintain.

Variable: A named storage location whose value can be changed.
Constant: A fixed value or non-modifiable object, depending on the form of constant being discussed.