Constants in C++ are immutable variables whose values cannot be modified once defined. They ensure data integrity by preventing accidental changes during program execution. This blog explores the syntax for declaring constants, various types (integer, character, floating-point, array, and structure constants), and their properties.
Learn how to use the const
keyword for defining constants, how constants differ from literals, and how the #define
directive and enum
keyword can also declare constants. Through examples and explanations, you’ll understand why constants are a vital part of robust and error-free coding. Perfect for programmers seeking to solidify their understanding of constants in C++.
—————————————-
const data_type var_name = value;
Example of constants:
Const int a=5;
Const int a=5; // write way of declaring constant
Const int a;
a=5;
// the above two lines are wrong way of declaring.
1.integer constants; const int a=10;
2.character constants; const char c=’a’
3.floating point constants; const float f=12.22f;
4.Double precision floating point constants;
double x = 3.141592653589793; // Pi with high precision
double y = -0.000123456789; // Negative double constant
double z = 2.718281828459045; // Euler’s number
5.Array constants
const int arr[] = {1, 2, 3, 4, 5};
6.Structure constants
#include <stdio.h>
struct Point {
int x;
int y;
};
int main() {
const struct Point p1 = {10, 20}; // A constant structure
printf(“Point: (%d, %d)\n”, p1.x, p1.y);
// p1.x = 30; // Error: Cannot modify a constant structure
return 0;
}
#include <stdio.h>
int main()
{
// declaring a constant variable
const int var;
// initialization after declaration
var = 30;
printf(“Value of var: %d”, var);
return 0;
}
Constants defined by using #define preprocessor directive.
Constants defined with #define act as macros, functioning like constant values.
Unlike regular constants, these are not managed by the compiler. Instead, they are processed by the preprocessor, which replaces them with their specified value before the compilation phase.
#include<stdio.h>
#define A 20
int main()
{
printf(“%d”,A);
}
There are three ways to declare the constants:
1.Using const Keyword:
#include<stdio.h>
#define A 20
int main()
{
const int a=30;
const float b=12.22f;
const double d=12.3345667;
printf(“%d”,A);
}
2.Using Macros
#include<stdio.h>
#define pi 3.14
int main()
{
printf(“%f”,pi);
}
3.Using enum Keyword:
// An example program to demonstrate working
// of enum in C
#include<stdio.h>
# define A monday
enum CalendarWeek{M, Tu, W, T, Fr, Sa, Su};
int main()
{
enum CalendarWeek day;
day = Wednesday;
printf(“%d”,day);
return 0;
}
Indian Institute of Embedded Systems – IIES