Skip to content

Trivia impact: rare

The Floating Literal With a p

a hexadecimal-looking number that is already a double

std::cout << 0x1.8p+1 << "\n";
std::cout << 0x1p-1 << "\n";

Does this compile? What does it print?

Answer
3
0.5

They are hexadecimal floating literals, not malformed hexadecimal integers.

Why

[lex.fcon] defines a hexadecimal floating literal as a base-16 significand followed by a binary exponent marked with p or P. 0x1.8 is hexadecimal 1 + 8/16, or 1.5, and p+1 scales it by 2^1, producing 3; 0x1p-1 is 1 * 2^-1. The exponent cannot use e, because e is already a hexadecimal digit and this form always scales by powers of two.

Where it shows up

They are handy in generated test data, low-level documentation, and numerical code that wants a value expressed as an exact binary fraction. Decimal notation is more familiar for most application constants, which keeps this spelling rare despite being standard C++.

Takeaway: 0x...p... spells a hexadecimal significand times a power of two.

Try it: g++ -std=c++17 main.cpp -o demo && ./demo

Open in Compiler Explorer ↗ Quiz this entry