Constant in C++

Constant can be referred as an entity that doesn’t change throughout the program. There are different types of constant available in c++ i.e. integer constant (whole number), floating point constant (number with decimal values), a character constant.


 


For Example:

Integer Constant= 37, 45

Floating Point Constant = 46.7, 57.8

Character Constant = This type of constant is written in single quotes i.e. ‘a’, ‘b’

String Constant = This type of constant is written in double quotes i.e. “Anita”, “Anmol”


In C++, There are two simpler techniques can be used to define constants.

  1. Using #definepreprocessor.
  2. Using constkeyword.
  3. #definepreprocessor

Syntax: #define identifier value

Example

#include <iostream>

using namespace std;

#define LENGTH 4 

#define WIDTH  8

#define NEWLINE '\n'

int main() {

   int area; 

   area = LENGTH * WIDTH;

   cout << area;

   cout << NEWLINE;

   return 0;

}

Result:

32


2) Using const keyword.

const prefix can be used to declare constants.

Syntax:

const type variable = value;

const int size = 4;


Leave a Reply

avatar
  Subscribe  
Notify of