CPP

Defining Constants

Constants refer to fixed values that the program may not alter and they are called literals.
Constants can be of any of the basic data types and can be divided into Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values.
Again, constants are treated just like regular variables except that their values cannot be modified after their definition.

There are two ways in C++ to define constants:

  • Using #define preprocessor.
  • Using const keyword.

The #define Preprocessor:

Following is the form to use #define preprocessor to define a constant:

Syntax:

#define identifier value

Following example explains it in detail:

Example:

#include <iostream.h>
#define PI 3.14
#define NEWLINE '\n'

int main()
{
    int radius = 10;
    float area;

    area = PI * radius * radius;  //area = PI r2
    cout << "Radius of Circle: " << radius;
    cout << NEWLINE;
    cout << "Area of Circle: " << area;
    return 0;
}

When the above code is compiled and executed, it produces the following result:

Output:

Command Prompt
Radius of Circle: 100
Area of Circle: 314

The const Keyword:

You can use const prefix to declare constants with a specific type as follows:

Syntax:

const type variable = value;

Following example explains it in detail:

Example:

#include <iostream.h>

int main()
{
    const float PI = 3.14;
    const char NEWLINE = '\n';
    int radius = 10;
    float area;

    area = PI * radius * radius;
    cout << "Radius of Circle: " << radius;
    cout << NEWLINE;
    cout << "Area of Circle: " << area;
    return 0;
}

When the above code is compiled and executed, it produces the following result:

Output:

Command Prompt
Radius of Circle: 100
Area of Circle: 314
Note that it is a good programming practice to define constants in CAPITALS.



Subscribe us on Youtube

Share This Page on


Ask Question