Constants:

Constants are quantities whose values do not change during program execution. They may be numeric or character. There are three types of constants:

  1. Numeric constants
  2. Character constants
  3. String constants
  4. Boolean constants

 

Numeric constants

Numeric constants consist of numbers. It can be further divided into two types.

  1. Integer constants:

Integers represent values that are counted, like the number of students in a class. An integer constant is a string of digits that does not include commas or a decimal point. Negative integer constants must be preceded by a negative sign. Some examples of valid integer constants are:

0, 453, -86, etc

  1. Floating point constants:

Floating point constants are numeric values with fraction or decimal point. Floating point constants represent values that are measured like the height of a person. Floating point constants are also called real constants.

EXAMPLES

54.6, 45.7, etc

 

Character constants

A character constant is one of the symbols or characters in C++ character set. Any character written within single quotation mark is known as character constant. All alphabetic characters, digits and special symbols can be used as character constants. The maximum length of a character constant is 1 character.

EXAMPLES

Some of the examples of character constants are:

‘S’, ‘3’, ‘=’, etc

Character constants usually includes digits 0 to 9, uppercase letters A to Z, lowercase letters a to z, punctuation symbols such as semicolon, comma, period, the special symbols such as +, -, =, etc

The combination of \n is known as escape sequence. The backslash indicates (\) that a special effect is needed and the character following backslash specifies what to do. Similarly the \t escape sequence is used to tab over eight characters.

EXAMPLE

#include<iostream>

Using namespace std;

int main ()

{

cout<<”hello\n world”;

return 0;

}

The output of the above program will be:

hello

world

 

String constants

A collection of characters written within double quotation mark is called string or string constant. It may consist of any alphabetic characters, digits and special symbols.

EXAMPLES

Some examples of string constants are as follows:

“City”, “country”, “123”, etc

 

Boolean Constants

Boolean constant can only store either true or false. There are two Boolean constants in C++

  1. True False

Defining a constant

There are two ways to define constants in C++ programming language.

  1. Using #define preprocessor
  2. Using const keyword

Using #define preprocessor

SYNTAX

#define identifier value

Identifier is the name of the constant and value is the value of the constant that will be fixed.

Using constant keyword

SYNTAX

const data_type  variable_name = value;