Constants in C++ are known as fixed values that the program cannot alter. Constants can use any of the basic data types, such as integers, floats, characters, strings and booleans. Constants in the code are treated like normal variables, except they cannot be altered.

Declaring constants

When you are declaring constants, it is a good programming practice to define constants in Capitals. There are two easy ways to declare constants:

  • Using the #define preprocessor
  • Using the const keyword

Example using #define

#include <iostream> 
using namespace std;
// Defined preprocessor values
#define BASE 10
#define HEIGHT 5
 
int main()
{
  int area;
 
  // This will give the calculation based on the
  // preprocessor values
  area = 0.5 * BASE * HEIGHT;
  cout << area;
 
  return 0;
}

 

Example using the const keyword

#include <iostream>
using namespace std;
 
int main()
{
  const int HEIGHT = 5;
  const int BASE = 10;
  int area;
 
  // This will give the calculation based on the
  // preprocessor values
  area = 0.5 * BASE * HEIGHT;
  cout << area;
 
  return 0;
}
Share this post