Section 3.3 - Numeric Literals

A number that is included in a program's source code is called a ``numeric literal''. There are two kinds of numeric literals: real literals and integer literals. A real literal includes a point (``.''), while an integer literal does not. Sample integer literals include ``2'' and ``400''. Sample real literals include ``2.0'', ``400.0'', and ``3.14159''.

Traditional exponent operators (such as 1.0E9) are permitted in numeric literals. Exponents are even allowed for integer literals, though for integer literals the exponent must not be negative.

To make long numbers easier to read, underscores are permitted inside a numeric literal. For example, "1_000_000" is legal. This is similar to the way commas are used in the United States and periods are used in Europe. Underscores aren't allowed to be consecutive, numbers may not end in an underscore, and underscores don't change the value of a number.

A useful Ada capability is its ability to write out literals in other bases from 2 to 16 (C has this capability to a lessor extent as well). These are called, reasonably enough, based literals. To create a based literal, write out the desired base, a "#" sign, the number in the requested base, and another "#" sign. For example, "2#1001_1000#" is a base 2 number equal to 128+16+8 = 152.

For completeness, here's the BNF of numeric literals:

numeric_literal ::= decimal_literal | based_literal
decimal_literal ::= numeral [ . numeral ] [ exponent ]
numeral ::= digit { digit | "_" }
exponent ::= "E" [ "+" | "-" ] numeral
based_literal ::= base "#" based_numeral "#" [ exponent ]
base ::= numeral
based_numeral ::= extended_digit { extended_digit | "_" }
extended_digit ::= digit | "A" | "B" | "C" | "D" | "E" | "F"


Quiz:

Here are two lists of numbers:

  1. 5.5, 200_000.12, 2#1000_0100#, 8#123#
  2. 60, 12, 0x50

Which of those lists has only legal numeric literals?

  1. List number 1.
  2. List number 2.

You may also:

PREVIOUS Go back to the previous section

NEXT     Skip to the next section

OUTLINE  Go up to lesson 3 outline

David A. Wheeler (dwheeler@dwheeler.com)

The master copy of this file is at "http://www.adahome.com/Tutorials/Lovelace/s3s3.htm".