0 votes
in C Plus Plus by
How do you define/declare constants in C++?

1 Answer

0 votes
by

In C++, we can define our own constants using the #define preprocessor directive.

#define Identifier value

Example:

#include<iostream.h>

#define PI 3.142

int main ()

{

                 float radius =5, area;

                 area = PI * r * r;

                 cout<<”Area of a Circle = “<<area;

}

Output: Area of a Circle = 78.55

As shown in the above example, once we define a constant using #define directive, we can use it throughout the program and substitute its value.

We can declare constants in C++ using the “const” keyword. This way is similar to that of declaring a variable, but with a const prefix.

Examples of declaring a constant

const int pi = 3.142;

const char c = “sth”;

const zipcode = 411014;

In the above examples, whenever the type of a constant is not specified, the C++ compiler defaults it to an integer type.

...