Why is n
in
const int n = -0123;
an octal literal? I thought that all octal literals had to start with a 0, and this one doesn't since it starts with a negative.
It's a small point I know but It's causing me great confusion!
Why is n
in
const int n = -0123;
an octal literal? I thought that all octal literals had to start with a 0, and this one doesn't since it starts with a negative.
It's a small point I know but It's causing me great confusion!
How is it possible that an octal literal can be negative?
There are no negative integer literals, only positive. The literal here is 0123 which does start with a 0 and is thus octal. -
in that expression is the unary minus operator.
This is absolutely true. However, the same applies to all integer literals - decimal, hexadecimal, octal, and binary. In fact, there are no negative integer literals. Expressions such as -1
apply the unary minus operator to the value represented by the literal, which may involve implicit type conversions (reference).
You seem to be mildly confused about literals, so:
In short, a literal is a way to describe a type that can be seen literally in the code. An integer is a literal because when you write, for example 4
in your code. You can literally see that it's the number four, and numbers are interpreted as int
s by default unless they have a dot (.
) after them, or any of the other valid suffixes.
However, you can tell to interpret it as an unsigned by writing 4u
. Now you can literally see that it's the number 4 interpreted as an unsigned. Likewise, the value "Hello World"
is a string literal because you can tell in the code that it is the string "Hello World
". On the other hand, a user defined class Person
has no literal way of being seen in the code. In C++14 you can however make user defined literals, but for a Person
that would still arguably make no sense. The standard library uses this in the <chrono>
header, defining literals such as s
, ms
and ns
for seconds, milliseconds and nanoseconds respectively.
When writing the octal -0123
you tell to interpret it as an octal value in the same way 0xFF
literally interprets as a hex. The -
sign is simply a way to apply the unary negation operator on the number 0123
.