Constants in C++

Notes:

Constants in C++ Programming Language:

What is a variable & constant?

Variable:
Variable is a named memory location, whose value can change during the execution of a program.

Constant:
Constant is a named memory location, whose value never changes during the execution of a program.

i.e. constants stay constant whereas variables vary.

Remember: While declaring itself; constants must be initialized in C++

Declaring & initializing constants:
- There are 2 different ways in which we can declare or define constants in C++ programming language the first way is using const keyword and other way is using #define preprocessor statement. Constants defined using #define preprocessor statement are called symbolic constants.

// Syntax for declaring and initializing a constant
const datatype NAME_OF_CONSTANT = value;
Ex:
const float PI = 3.142;

OR

#define NAME_OF_CONSTANT value
Ex:
#define PI 3.142

Note: Constants must be initialized when they are declared.

// Syntax for declaring and initializing multiple constants
const datatype NAME_OF_CONSTANT1 =value, NAME_OF_CONSTANT2 =value,...;
Ex:
const float PI = 3.142, E = 2.71828;

OR

// we cannot declare and initialize multiple constants on a single line using #define
Ex:
#define PI 3.142
#define E 2.71828

Example Code:

#include <iostream>
using namespace std;

/*
#define PI 3.142
#define E 2.71828
*/

int main()
{
/*
int playerScore = 0;
cout << "player score = " << playerScore << endl; // 0

playerScore = 10;
cout << "player score = " << playerScore << endl; // 10

const float PI = 3.142;
cout << "PI = " << PI << endl;

const float E = 2.71828;
cout << "E = " << E << endl;

cout << "PI = " << PI << endl;
cout << "E = " << E << endl;
*/

const float PI = 3.142, E=2.71828;
cout << "PI = " << PI << endl;
cout << "E = " << E << endl;

return 0;
}