Thursday, September 1, 2011

The const qualifier in C++ programs


Todays topic in our C++ tutorial is const qualifier.

 If a const keyword precedes the data type of a variable, it means that the variable will not change it’s value throughout the program. Variables with this qualifier are often named in all uppercase, as a reminder that they are constants. const keyword replaces #define statement in C. const is a better idea as compared to #define because it’s scope of operation can be controlled by placing it appropriately either inside a function or outside all functions. If a const variable is declared inside a function that means it becomes local variable to that function which is not possible with #define statement. Like const variables, there can be const pointers also. const pointer will point a fixed value and it can not changed although the pointer can hold the address of other variable.

C++ program to demonstrate use of const in pointer

#include< iostream.h >
#include< conio.h >
void main()
{
clrscr();
int a,b;
const int *ptr;
ptr=&a;
cout<< "Enter values for 'a' and 'b':";
cin>>a>>b;
cout<<endl<<"Value of 'a' through pointer:"<< *ptr;
//  ptr=19; / wrong it can not change value */
ptr=&b;
cout<< endl<< "Value of 'b' through pointer:"<< *ptr;
getch();
}

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner