Defining Constants:
There are two simple ways in C++ to define constants:
- Using #define preprocessor.
- Using const keyword.
#define
#define identifier value
Following example explains it in detail:
#include <iostream>
using namespace std;
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}
Result:
50
const
const type variable = value;
Following example explains it in detail:
#include <iostream>
using namespace std;
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}
Result:
50
Note that it is a good programming practice to define constants in CAPITALS.
No comments:
Post a Comment