C++ Constants

Constants are fix values that a program don’t change, they are also known as literals. Constants are the values that can’t be change after their initialization. Constants could be of any basic data types for example; integer, character, floating point, string etc.

C++ Integer Constants

Integer constants have no fractional values in their data element. You could specify integer constant in decimal, Oct or hexadecimal.

0 for octal

0X for hexadecimal

Nothing fot decimal

Integer constant also include suffix, combination of unsigned and long.

Examples

354u

725

In decimal 76

In hexadecimal 0x9c

In octal 0654

In unsigned int 50u

In long type 78l

In unsigned long 64ul

C++ Character constants

A character constant is a character that is enclosed within single quotation marks(‘ ‘).  You can code any character you want by placing it’s octal value after backslash. A character constant could be a plain char or a universal char.

Some specific characters that are used for special purpose along with backslash.

For example

For horizontal tab (\t)

For vertical tab (\v)

For new line (\n)

For backspace (\b)

Carriage return (\r)

For form feed (\f) etc.

C++ String constants

String having characters that are similar to character constants. String constants enclosed in double quotes (” “). Long lines could be break down into small lines using string constants.

C++ Floating point Constants

Floating point constants could be represent in decimal form or exponential form.

The method of using decimal form is, you have to include the exponent or decimal point or both.

The method of using exponential form is, you have to include the fractional part or integer part or .

Examples

536418-3L

5.6724 etc

C++ Boolean Constants

Boolean constants are of two types;

  • True
  • False

C++ Defining Constants

In C++ there are two ways to defining constants:

  1. Const keyword.
  2. #define preprocessor.

C++ const keyword

Const keyword could be used for the declaration of pointer. They are also use in declaration of constants with a specific types.

Syntax:

Const data type = value;

Example

Const int = 25;

Const char = ‘b’; etc.

#define Preprocessor

Preprocessor is the direction to the compiler to preprocess the information before compilation starts. As all preprocessor directives starts with #.

Syntax:

#define identifier value

Example

#define marks 5

#define total-marks 10

#define grade ‘A’ etc