5 - Constants in C++
5 - Constants in C++
1
Constant:
an entity that can not be changed during program execution.
Constants refer to fixed values that the program may not alter
and they are called literals.
3
Rules for constructing Real Constants
1. Real constants are often called Floating Point constants.
2. The real constants could be written in two forms—Fractional form
and Exponential form.
Rules for constructing Real Constants(fractional)
1. A real constant must have at least one digit
2. It must have a decimal point
3. It can be either positive or negative
4. Default sign is positive
5. No commas or blanks are allowed within a real constant
Example: 0.3, -890.7, +98.33, 0.08
4
Rules for constructing Character Constants
5
Defining Constants:
There are two simple ways in C++ to define constants:
6
Following example explains it in detail:
Execute:
#include <iostream>
using namespace std;
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
When the above code is compiled and executed, it
int main()
{
produces the following result:
50
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
7
return 0;
}
2. The const Keyword:
You can use const prefix to declare constants with a specific type as follows:
8
#include <iostream>
using namespace std;
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
When the above code is compiled and executed, it
int area; produces the following result:
50
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0; 9
}
Thanks
10