Go gotcha: Numbers that start with zero
What's going on with the counting in this example?
const (
Century = 100
Decade = 010
Year = 001
)
// The world's oldest person, Emma Morano, lived for a century,
// two decades and two years.
fmt.Println("She was", Century+2*Decade+2*Year, "years old.")
She was 118 years old.
Answer
010
is a number in base 8, therefore it means 8, not 10.
Integer literals in Go are specified in octal, decimal or hexadecimal. The number 16 can be written as 020
, 16
or 0x10
.
Literal | Base | Note |
---|---|---|
020 |
8 | Starts with 0 |
16 |
10 | Never starts with 0 * |
0x10 |
16 | Starts with 0x |
* 0
is an octal literal in Go.
An integer literal is a sequence of digits representing an integer constant. An optional prefix sets a non-decimal base: 0 for octal, 0x or 0X for hexadecimal. The Go Programming Language Specification: Integer literals
Comments
Be the first to comment!