Using the const variable modifier in C++ program to declare the constant variable

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info:

To do: Declaring and using the constant variable in C++ programming

To show: The const usage in C++ program declaring constant variable

 

// Demonstrates type casting

#include <iostream>

using namespace std;

 

double funct1(double& f)

{

// do some work here...

f++;

cout<<"f = "<<f<<endl;

// return the incremented value...

return f;

}

 

// const argument, can't be modified...

void funct2(const double& d)

{

cout<<"d = "<<d<<endl;

// remove const...

// use the non-const argument, making function call...

double value = funct1(const_cast<double> (d));

// display the returned value...

cout<<"value = "<<value<<endl;

}

 

int main(void)

{

double c = 4.324;

 

// first function call...

funct2(c);

 

return 0;

}

 

Output example:

 

d = 4.324

f = 5.324

value = 5.324

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index