Constants In C++

Constants in C++ refer to variables with fixed values that cannot be changed. Once they are defined in the program, they remain constant throughout the execution of the program. They are generally stored as read-only tokens in the code segment of the memory of the program.

Methods of Defining a Constant in C++ program:-

  • By using the const keyword
  • By using #define preprocessor

Constant Definition Using const Keyword

Defining constants using const keyword is one of the older methods that C++ inherited from C language. In this method, we add the const keyword in the variable definition as shown below:

Syntax:-

const type constant_name = value;

One thing to note here is that we have to initialize the constant variables at declaration. Otherwise, the variable will store some garbage value and we won't be able to change it.

const int var;

const int var = 5;

Example:-

#include <iostream>
using namespace std;
 
int main()
{
    const int SIDE = 50;
    int area;
 
    area = SIDE*SIDE;
 
    cout<<"The area of the square with side: " << SIDE <<" is: " << area << endl;
 
    return 0;
}

Output:-

The area of the square is: 2500

Note: constcan also be declared like this int const SIDE = 50

Constant Definition Using #define preprocessor

We can also define constants using the #define. Constants created using the #define preprocessor are called “macro constants”. Unlike the other methods, constants defined using this method simply work as an alias for their value which is substituted during preprocessing.

It is the less preferable way to define a constant in C++ due to the lack of type safety.

Syntax:-

#define MACRO_NAME replacement_value;

We use the #define directive to create a macro. First, we start with the #define directive, followed by the name we want to give to our macro. Then, we provide a replacement value for the macro. Whenever the preprocessor encounters this macro in our code, it will replace it with the specified value.

Example:-

#include <iostream>
using namespace std;
 
// using #define to create a macro
#define Side 5
 
int main()
{
    // using constant
    const double area = Side * Side;
 
    cout << "The area of square with side 5 is ";
    cout << area;
 
    return 0;
}

Output:-

The area of square with side 5 is 25

Types Of Constants

  1. Numeric Constant

    • Integer Constants
    • Floating-point Constants
  2. Non-Numeric Constant (Character Constant)

    • Single Character constants
    • String Constants
TypesOfConstants

Numeric Constant

These have numeric value having combination of sequence of digits i.e. from 0-9 as alone digit or combination of 0-9 with or without decimal point (precision value) having positive or negative sign. These are further sub-divided into two categories as:

  1. Integer Numeric Constant

  2. Floating-point Constants or Real Numeric Constant

Integer Constants

Integer constants are sequences of integers with a fixed value. They must not contain any decimal points or fractional numbers. Integer constants can either be positive or negative numbers. They include decimal system integers, octal system integers, hexadecimal system integers.

  1. Decimal integers - Set of digits ranging from 0 to 9. For Example - const int e = 5;

  2. Octal integers - Set of digits ranging from 0 to 7 which start with the number '0' in the beginning/at the prefix. For example - const int l = 032;

  3. Hexadecimal integers - Set of digits ranging from 0 to 9 and alphabets from A to F where A indicates number 10 and F indicates number 15. 0x is used at the prefix of the value. For example - const int d = 0x14;

    #include <iostream>
    using namespace std;
     
    int main()
    {
      const int e = 5; //using 'const' keyword
      const int l = 032; //octal constant
      const int d = 0x14; //hexadecimal constant
     
      cout << "Integer constant is : " << e << endl;
      cout << "Octal constant is : " << l << endl;
      cout << "Hexadecimal constant is : " << d << endl;
     
      return 0;
    }

    Output:-

    Integer constant is : 5
    Octal constant is : 26
    Hexadecimal constant is : 20

Floating Point Constants

Floating-point constants are used to represent floating-point values that cannot be changed. They are further divided into two parts. One is Mantissa Part and the other is Exponent Part.

  • Mantissa part: The part without E and having a decimal point is called Mantissa Real part. It is also called without exponent part.For eg:-

     const float f = 283.91;
  • Exponent part: The exponent part has an E within it. It is also called a scientific notation. Here E has base value 10. it computes the power. For example:-

    const float e = 2.2E2;  //Here 2.2E2 means 2.2 X 10^2 => 220

Character Constants

Character constants in C++ are single characters enclosed in single quotes, such as 'A', ' ' or '\n'. They can be used to represent characters in the execution character set, which is the character set on the machine where the program is executed. For example, the character 'A' would be represented as the number 65 in the ASCII character set.

Character constants can also be used to represent special characters, such as the newline character '\n' or the tab character '\t'. These characters are represented by escape sequences , which are sequences of characters that are interpreted by the compiler. For example, the escape sequence '\n' is interpreted as the newline character.

Character constants can be used in a variety of ways in C++ :-

  1. Single Character Constant

    Any single character from the defined character set is called a character constant. They include a single alphabet, single-digit, single symbol enclosed within single inverted commas. For example: 's', 'L', 'd', '+', '7' etc. are some valid single character constant.

     const char s = 'S', d = 'D';
  2. String Constant

    A string is a set of characters enclosed in double quotes ("). For example: "Eniv Studios" is a string. You must not confuse strings with characters. A single character constant is enclosed in single quotes, as in 'd'. However, "d" is a string containing only one letter. For example: "Shubham", "Eniv", "2001", "2020-2024" etc. are some valid string character constant.

    #include <iostream>
    using namespace std;
     
    int main()
    {
      const char d = 'D';                //Single Character Constant
      const string s = "Eniv Studios";   //String Character Constant
     
      cout << "Single Character Constant Is : " << d << endl;
      cout << "String Character Constant Is : " << s << endl;
     
      return 0;
    }

    Output:-

    Single Character Constant Is : D
    String Character Constant Is : Eniv Studios

Advantages of Constants

  • Immutability - It is useful if you know that the value of the variable will not change throughout your program lifecycle.
  • Code Maintenance - If you need to use the Constant value multiple times in your program, assigning it to a variable and then using that variable will save time.
  • Memory Allocation - It is generally stored in program memory (ROM) and not in the main memory(RAM) of the computer thus providing faster execution speed.
How's article quality?

Last updated on -

Page Contents