The const variable usage in C program

 

 

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: Some math operations

To show: The const variable usage in C program

 

// const variable

#include <iostream>

using namespace std;

 

int main(void)

{

// p = 10 is a constant value, cannot be modified during the program execution...

const int p = 10;

cout<<"q = p + 20 = "<<(p + 20)<<" where, p = 10"<<endl;

 

// The following code should generate error, because we try to modify the constant value...

// uncomment, recompile notice the error...

//p = 15;

//--p;

}

 

Output example:

 

q = p + 20 = 30 where, p = 10

Press any key to continue . . .

 

 

Uncommenting the last 2 lines of codes and re-run the program.

 

// const variable

#include <iostream>

using namespace std;

 

int main(void)

{

// p = 10 is a constant value, cannot be modified

// during the program execution...

const int p = 10;

cout<<"q = p + 20 = "<<(p + 20)<<" where, p = 10"<<endl;

// The following code should generate error, because

// we try to modify the constant value...

// uncomment, recompile notice the error...

p = 15;

--p;

}

 

The following errors should be expected.

 

error C3892: 'p' : you cannot assign to a variable that is const

error C2105: '--' needs l-value

 

 

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