Constants are the identifiers whose values do not change. While values of variables can be changed at any time, values of constants can never be changed. Constants are used to define fixed values like mathematical constant PI or the change on an electron even by mistake.

A constant is an explicit data value specified by the programmer. The value of the constant is known to the compiler at the compile time. C allows the programmer to specify constants of integer type, floating point type, character type, and string type.

  • storage-classes-in-c-programming-language-for-beginnersInteger Constants: A constant of integer type consists of a sequence of digits. For example, 1,23,6,89646 are valid integer constants.

A literal integer like 1235 is of type int by default. For a long integer constant the literal is succeeded with either ‘L’  or ‘l’ (like 1234567L). Similarly, an unsigned int literal is written with a ‘U’ or ‘u’ suffix (example 12U). Therefore, 1234L, 1234l, 1234U, 1234u and 1234Ul all are valid integer constants.

Integer literals can be expressed in decimal, octal, or hexadecimal notation. By default an integer is expressed in 0 through 9, preceded by an optional – or + sign.

While writing the integer constants, the embedded spaces, the commas, and non-digit characters are not allowed in C. Therefore, integer constants given below are totally invalid in C.

123 456

12, 34, 567

$123

An integer constant preceded by a 0(zero) is an octal number. Octal integer consists of a set of digits, 0 through 7.

Similarly, an integer constant is expressed in hexadecimal notation if it is preceded with 0x or 0X. Hexadecimal number contains digits from 0-9 and letter A to F, which represents numbers through 10 to 15.

 Floating Point Constants: Integers are inadequate to express numbers that have a fractional part. A floating point constant consists of an integer part, a decimal point, a fractional part, and an exponent field containing e or E (e means exponent) followed by an integer where the fraction part and integer part are a sequence  of digits. However, it is not necessary that every floating point number must contain all these part.

A literal like 0.007 is treated as of type double by default. To make it a float type literal, you must specify the suffix F or f.

Character Constants: Characters are inadequate to represent the alphabets that is ‘a’ or ‘A’ to ‘z’ or ‘Z’. A character constant consist of only alphabets which is enclosed in a single quote (‘ ’). A literal like a, b, c are treated as of type character.

String Constants: String is the group of character that are in combined form and this literal is enclosed by double quotes (“  ”). Example: “abc”, “validity”, etc.

There are two ways to define constants in C:

  1. #define preprocessor
  2. By using const keyword