C++ Builder Tutorials

Constants / Literals in C++

Constants refer to fixed values that the program may not alter. They are also called literals.
They can be: integer numbers, floating-point numbers, characters, Strings or a Boolean values.


Declaration of constants

You can directly use constant values in statements, such as:

 b = a + 20;   // 20 is a literal integer

But you can also declare a constant with the keyword const followed by its type, its name and a value assignment, as follows:

 const type variable = value;

Example:

int SomeFunction() 
{
  const float LENGTH = 10;
  const float WIDTH  = 5.5;
  float Area;  
  Area = LENGTH * WIDTH;
  ...
}

It is a good convention to write the names of constants in CAPITALS.

Integer constants

An integer constant can be a decimal, octal, or hexadecimal number.
It can have a prefix that specifies the base or "radix": 0x or 0X for hexadecimal, 0 for octal.
An integer constant can also have a suffix that is a combination of U and L, for unsigned and long, respectively. These suffixes can be uppercase or lowercase and can be in any order.

Examples:

15        // decimal signed integer
15u       // decimal unsigned integer
0xFL      // hexadecimal long integer (equals decimal 15)
0234      // octal
0x4b      // hexadecimal

Floating-point constants

A floating-point constant has an integer part, a decimal point, a fractional part, and can have an exponent part. The exponent is preceded by e or E.

Examples:

const float X = 3.14159;
const double Y = 314159E-5;

Boolean constants

A Boolean constant can be assigned one of two values: true or false.

Examples:

const bool SUNNY = true;
const bool RAINING = false;

Character constants

The value of a character constant is enclosed in single quotes.
If it begins with L (uppercase!), it indicates a wide character literal (such as L'a'). Otherwise, it is a narrow character literal (such as 'a').

A character constant can be:

  • a plain character, such as 'a'
  • an escape sequence, such as '\t'
  • a universal (unicode) character, such as '\u02C0'

If certain characters are preceded by a backslash, they will have special meaning. Backslash is called the "escape" character.

Examples of escape sequence codes:

\\ 	\ character
\' 	' character
\" 	" character
\n 	Newline
\r 	Carriage Return

String constants

String constants are enclosed in double quotes.
A String value contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.

You can break a long line into multiple lines by separating them using whitespaces.

String isn't a basic data type, but it's a class!
The type indicator String must start with a CAPITAL S.

Examples:

const String HELLO = "Hello, programmer";
const String LONGLINE = "This is a long line,
a very long line, a really long line, a very very long line, a very very very long line";