What is constants ? | Difference between constant and variable | How we define a constant ?

What is constant?
The constants are the quantity whose value can’t be change or modified during the execution of the program. The concept of constants is same as the variable but the value of constant can’t be over write as variable. The constant must be defined before use and as variable it can't be define by cin. We must define it by a prescribe method.

Defining Constants:
There are two simple ways in C++ to define constants:
  • Using #define preprocessor.
  • Using const keyword.

The #define Preprocessor:
Following is the forms to use #define preprocessor to define a constant:

#define identifier value

Following example explains it in detail:
#include <iostream>

using namespace std;



#define LENGTH 10  // a constant define

#define WIDTH  5 // a constant define

#define NEWLINE '\n'//constant define for new line



void main(void)



{

   int area;


   area = LENGTH * WIDTH;


   cout << area;

   cout << NEWLINE;

}
When the above code is compiled and executed, it produces the following result: 50
The const Keyword:
You can use const prefix to declare constants with a specific type as follows:

const type variable = value;
Following example explains it in detail:



#include <iostream>

using namespace std;



void main(void)



{const int  LENGTH = 10; // define a constant

   const int  WIDTH  = 5; // define a constant

   const char NEWLINE = '\n'; // constant for new line



   int area;



   area = LENGTH * WIDTH;

   cout << area;

   cout << NEWLINE; 
}

Comments

Popular posts from this blog

Umbrella activities in Software Engineering

Operating System | Best Definition of Opetating System