Type Qualifiers in C++

In this tutorial we will learn about qualifies in c+ +. What are the uses of qualifiers and where we use them. Let see with some examples.

What are the type Qualifiers in C++?

C++ includes two type qualifiers –keywords

  1. constant
  2. volatile

The nature and behavior of variables with respect to whether the compiler permits the program to modify the variable.
You provide the type qualifier keyword when you declare the variable, as shown here:

const int x=123;
volatile char ch;

const

  • A const variable is the one the program may not modify except initialization when the variable is declared.
  • When a variable is qualified as constant, the compiler prevents the program from accidentally modifying the variable’s contents.
  • You can override this restriction with the const_cast operator.

volatile

  • A volatile variable is the opposite of a constant variable.
  • The volatile type qualifier tells the compiler the program could be changing the variable in the unseen ways.
  • Those ways are implementation-dependent.
  • One possibility is by an asynchronous interrupt service routine.
  • The compiler must know about such a variable, so the compiler does not optimize its access in ways that would defeat the external changes.
  • The volatile type qualifier tells the compiler not to make such optimizations.

Const Versus #define

C++ programmers often use a const declaration where c programmers before them used the #define pre-processor directive to equate a symbol with a value.

A const Variable?

  1. The phrase, const variable, seems to be an oxymoron.
  2. How can something be a constant and variable at the same time?
    The use is, nonetheless, common among programmers and writers about programming, and  I won’t try to change it.

Program to implement const Qualifier

#include<iostream>
using namespace std;
int main()
{
const int mx =300; // const variable declaration
for(int ctr =100; ctr< mx; ctr +=50 )
cout<<"ctr = "<<ctr <<"\n";
}

Output from Program

ctr = 100
ctr = 150
ctr = 200
ctr = 250

Program to implement  volatile Type Qualifier

#include<iostream>
using namespace std;
volatile int val = 300; // volatile declaration
int main()
{
for (int ctr =100 ; ctr < val; ctr +=50)
cout<<"ctr: "<<ctr <<"\n";
}

Output from Program

ctr: 100
ctr: 150
ctr: 200
ctr: 250

Also, read:

 

Leave a Reply

Your email address will not be published. Required fields are marked *