C Constants
Q1. Define C Constants.
Answer:
Constants in C are the immutable variables whose values cannot be modified once they are declared in the C program.
Q2. What is the use of the const keyword?’
Answer:
The const keyword is the qualifier that is used to declare the constant variable in C language.
Q3. Can we initialize the constant variable after the declaration?
Answer:
No, we cannot initialize the constant variable once it is declared.
Q4. What is the right way to declare the constant in C?
Answer:
The right way to declare a constant in C is to always initialize the constant variable when we declare.
Q5. What is the difference between constant defined using const qualifier and #define?
Answer:
The following table list the differences between the constants defined using const qualifier and #define in C:
Constants using const Constants using #define They are the variables that are immutable They are the macros that are replaced by their value. They are handled by the compiler. They are handled by the preprocessor. Syntax: const type name = value; Syntax: #define name value
Q6. Is there any way to change the value of a constant variable in C?
Answer:
Yes, we can take advantage of the loophole created by pointers to change the value of a variable declared as a constant in C. The below C program demonstrates how to do it.
C
// C Program to change the value of constant variable
#include <stdio.h>
int
main()
{
// defining an integer constant
const
int
var = 10;
printf
(
"Initial Value of Constant: %d\n"
, var);
// defining a pointer to that const variable
int
* ptr = &var;
// changing value
*ptr = 500;
printf
(
"Final Value of Constant: %d"
, var);
return
0;
}
OutputInitial Value of Constant: 10 Final Value of Constant: 500Related Article – Const Qualifier in C
Constants in C
The constants in C are the read-only variables whose values cannot be modified once they are declared in the C program. The type of constant can be an integer constant, a floating pointer constant, a string constant, or a character constant. In C language, the const keyword is used to define the constants.
In this article, we will discuss about the constants in C programming, ways to define constants in C, types of constants in C, their properties and the difference between literals and constants.