- Literal Constant
- A literal constant or simply a literal is a value, such as a number, character, or string that may be assigned to a variable or symbolic constant, used as an operand in arithmetic or logical operation, or as a parameter to a function.
- Literals are hardcoded values such as the number 5, the character 'A', or the string, "Hello, world!".
- Numeric literals may be represented in a variety of formats (decimal, hexadecimal, binary, floating-point, etc.)
- A literal always represents the same value (5 always represents the quantity of five.)
Constant vs. Literal
Although most of the C programming world uses the terms "constant" and "literal" interchangeably, those with assembly language background will understand them to describe two distinctly different, though related, concepts.
The above are two ways to create constants for use in our programs.
The numbers 32767 and -32768 are literals. They are actual values and the symbols we use to represent them cannot ever mean anything other than the values they represent.
The words MAXINT and MININT are constants. They are symbols used to represent the values we assigned to them (32767 and -32768 respectively), but the symbols could mean anything we want. If you just saw MAXINT somewhere alone, you wouldn't know what its value was until you saw the assignments above. However, once a value has been assigned to MAXINT, its value may never change (unlike a variable), which makes it a constant.
So, in this class:
- Constants are symbols/labels that represent literal values that we assign to them.
- Literals or Literal Constants are values, often assigned to symbolic constants or variables, but just as often used on their own.
Types of Literals
There are four basic types of literals:
These types do not have a one to one relationship with the data types we discussed earlier. As we will see later, both char and int may be used with integer literals.
Integer and Floating-Point literals are numeric types and share some common rules:
- Commas and spaces are not allowed.
- Value cannot exceed type bounds (without automatic truncation).
- May be preceded with a minus sign "-".
In the next few lessons, we will look at each literal type in detail.