1

The value i is 1, but why is i still 1 after sizeof(i++)? I only know sizeof is an operator.

int main() {
    int i = 1;
    sizeof(i++);
    std::cout << i << std::endl;  // 1
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Yongqi Z
  • 605
  • 8
  • 20
  • 2
    Because `sizeof` is evaluated at compile time, and its operand is ever evaluated at all, so `i++` is never executed. Don't write code like this. – user207421 Jun 25 '22 at 01:23

1 Answers1

3

sizeof does not evaluate its operand. It determines the operand's type and returns its size. It is not necessary to evaluate the operand in order to determine it's size. This is actually one of the fundamental core principles of C++: the types of all objects -- and by consequence of all expressions -- is known at compile time.

And since the operand does not get evaluated there are no side effects from its evaluation. If you sizeof() something that makes a function call the function does not actually get called: sizeof(hello_world()) won't call this function, but just determines the size of whatever it returns.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148