Skip to content

Intermediate Gotchas

The Increment sizeof Never Performed

the counter is mentioned, but never changes

int main() {
  int retries = 0;
  const auto bytes = sizeof(++retries);

  std::cout << "bytes: " << bytes << '\n';
  std::cout << "retries: " << retries << '\n';
}

Run it. Did asking for the size increment retries?

Answer
bytes: 4
retries: 0

The expression has a type, but its increment never runs.

Why

sizeof determines its result from the operand's type and leaves the operand unevaluated. ++retries has type int, but no increment occurs, so retries remains zero. The 4 is the observed size of int on this compiler, not a portable promise. GCC emits no warning under -Wall -Wextra because the expression is valid.

The fix

Do the effect separately from the query:

++retries;
const auto bytes = sizeof(retries);

Takeaway: an operand of sizeof supplies a type, not a value to evaluate.

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

Open in Compiler Explorer ↗ Quiz this entry