Skip to content

04 Beginner The Hundred

The Leading Zero

the padding that changes the number

#include <iostream>

int main() {
    // tickets sold per day, zero-padded so the columns line up
    int sales[] = {110, 052, 007, 004};

    int total = 0;
    for (int s : sales)
        total += s;

    std::cout << "total: " << total << "\n";   // 110 + 52 + 7 + 4 = 173... right?
}

Run it. What does it print?

Answer

total: 163. That tidy 052 is the number 42.

Why

A leading zero is not decoration — it is C++'s octal prefix, inherited straight from C. 052 means 5×8 + 2 = 42, while 007 and 004 survive by luck: digits below 8 mean the same in base 8 as in base 10. So zero-padding a column silently rewrites some values and not others, and -Wall -Wextra says nothing — every literal here is perfectly legal. The trap only announces itself when an 8 or 9 sneaks in; main.cpp keeps one waiting behind -DSHOW_BUG, and GCC 11.5 refuses it:

error: invalid digit "9" in octal constant

The fix

Strip the zeros — and if a column really has to line up, pad the output (std::setw from <iomanip>), never the literal:

int sales[] = {110, 52, 7, 4};

For the times you want another base, say so explicitly: 0x2A (hex), 0b101010 (binary, since C++14), and 1'000'000 (digit separators, also C++14) all beat a bare leading zero.

Takeaway: 0 at the front of an integer literal means base 8 — never zero-pad a number in source code.

Try it: g++ -std=c++17 main.cpp -o demo && ./demo — add -DSHOW_BUG to meet the error.

Open in Compiler Explorer ↗ Open SHOW_BUG variant ↗ Quiz this entry