Q:

Example of declaring and printing different constants in C++

0

Example of declaring and printing different constants in C++

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Consider the program:

#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

Here, I am trying to change the value, consider the program...

#include <iostream>
#include <string.h>
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)         
              ^      

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Most popular and Searched C++ solved programs with Explanation and Output

Similar questions


need a help?


find thousands of online teachers now
How to skip some of the array elements in C++?... >>
<< C++ program to demonstrate example of delay() func...