Integer Literals
Integer literals may be expressed in a variety of formats. The sections below describe the rules for each format and provide examples.
Decimal (base 10)
Rules
- Cannot start with 0 (except for 0 itself), that would make it octal.
- Cannot include a decimal point - that would make it floating point, even if the fractional part is 0.
- Cannot include commas or spaces.
- Must use only the digits zero-nine.
- May be preceded by a minus sign "-".
Examples of Valid Decimal Integers
0 | 5 | 127 | -1021 | 65535 |
Examples of Invalid Decimal Integers
32,767 | 25.0 | 1 024 | 0552 | 7A |
Hexadecimal (base 16)
Rules
- Must begin with 0x or 0X.
- May use digits zero-nine and the letters A-F or a-f (not case sensitive).
- Cannot include a decimal point.
- Cannot include commas or spaces.
- May be preceded by a minus sign "-".
Examples of Valid Hexadecimal Integers
0x | 0x1 | 0x0A2B | 0x12 | 0xBEEF |
Yes, 0x is legal and represents a value of 0. However, nobody uses 0x alone, except perhaps in The International Obfuscated C Code Contest.
Examples of Invalid Hexadecimal Integers
0x5.3 | 0EA12 | 0xEG | 53h |
Octal (base 8)
While octal is still part of the ANSI/ISO C specification, almost no one uses it anymore.
Rules
- Must begin with 0.
- Must use only the digits zero-seven.
- Cannot include a decimal point.
- Cannot include commas or spaces.
- May be preceded by a minus sign "-".
Examples of Valid Octal Integers
01 | 012 | 073125 |
Examples of Invalid Octal Integers
05.3 | 0o12 | 080 | 53o |
Binary (base 2)
ANSI C does not specify a format for binary integer literals. However, this quasi-standard notation is supported by many compilers for embedded microcontrollers. If your code must be ANSI compliant, do not use this notation.
Rules
- Must begin with 0b or 0B.
- Must use only the digits zero-one.
- Cannot include a decimal point.
- Cannot include commas or spaces.
- May be preceded by a minus sign "-".
Examples of Valid Binary Integers
0b | 0b1 | 0b0101001100001111 |
Examples of Invalid Binary Integers
0b1.0 | 01100 | 0b12 | 10b |