Home »
C++ programs »
C++ Most popular & searched programs
Example of declaring and printing different constants in C++
Declaring and printing different constant in C++: Here, we will learn to declare and print the value of different type of constants using C++ program.
[Last updated : February 26, 2023]
Declaring and printing different constants
Constant
Constants can be declared by using "const" keyboard and value of constants can never be changed during the program’s execution.
Syntax:
const data_type constant_name = value;
Read: constant declaration in C/C++
In this program, we are declaring 4 constants:
- String constant (character array constants): MY_NAME and MY_ADDRESS
- Integer constant: MY_AGE
- Float constant: MY_WEIGHT
C++ code to declare and print the different constants
#include <iostream>
using namespace std;
int main() {
// declaring constants
const char MY_NAME[] = "Master Satendra Sharma";
const char MY_ADDRESS[] = "New Delhi, INDIA";
const int MY_AGE = 17;
const float MY_WEIGHT = 50.25f;
// printing the constants values
cout << "Name: " << MY_NAME << endl;
cout << "Age: " << MY_AGE << endl;
cout << "Weight: " << MY_WEIGHT << endl;
cout << "Address:" << MY_ADDRESS << endl;
return 0;
}
Output
Name: Master Satendra Sharma
Age: 17
Weight: 50.25
Address:New Delhi, INDIA
Another Example
Here, I am trying to change the value, consider the program...
#include <string.h>
#include <iostream>
using namespace std;
int main() {
// declaring constants
const char MY_NAME[] = "Master Satendra Sharma";
const char MY_ADDRESS[] = "New Delhi, INDIA";
const int MY_AGE = 17;
const float MY_WEIGHT = 50.25f;
// changing the value
MY_AGE = 18; // ERROR
MY_WEIGHT = 60.0f; // ERROR
strcpy(MY_NAME, "RAHUL"); // ERROR
// printing the constants values
cout << "Name: " << MY_NAME << endl;
cout << "Age: " << MY_AGE << endl;
cout << "Weight: " << MY_WEIGHT << endl;
cout << "Address:" << MY_ADDRESS << endl;
return 0;
}
Output
main.cpp: In function 'int main()':
main.cpp:14:9: error: assignment of read-only variable 'MY_AGE'
MY_AGE = 18; //ERROR
^
main.cpp:15:12: error: assignment of read-only variable 'MY_WEIGHT'
MY_WEIGHT = 60.0f; //ERROR
^
main.cpp:16:24: error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
strcpy(MY_NAME,"RAHUL"); //ERROR
^
In file included from main.cpp:2:0:
/usr/include/string.h:125:14: error: initializing argument 1 of 'char* strcpy(char*, const char*)' [-fpermissive]
extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
^