-1
int main() {
    int n = 1;
    sizeof(n++);
    printf("%d",n);
    return 0;
}

It's part of my code. The output is 1. But why is n not increased by 1?
I tried that for other functions but for others output was 2.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    `sizeof n++` equates to *"sizeof type(n++)"* (if this existed). the size of of a type does not change no matter what value it has: `sizeof 42` == `sizeof -3` == `sizeof isalpha('x')` == `sizeof (int)`. – pmg Nov 15 '18 at 13:17

3 Answers3

3

This is because, sizeof is not a function, it is a compile time operator, ans unless the operand is a VLA, the operand is not evaluated at runtime.

Quoting C11, chapter §6.5.3.4

[...] If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

To add a little on why it does not need to evaluate the operand, from the semantics of the operand,

[....] The size is determined from the type of the operand. [...]

and, the type of the operand is fixed and known at compile time (unless a VLA), so it does not need to evaluate the operand to perform it's job anyway. In your case, since n is of type int

 sizeof (n++);

is just the same as

 sizeof (int);
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
3

sizeof is not a function, it's an operator.

sizeof(n++) is equivalent to sizeof n++, which (since n is an int) is equivalent to sizeof (int).

sizeof only looks at the type of its operand; it doesn't evaluate expressions.

(Unless variable-length arrays are involved, but we're going to ignore that for now.)

melpomene
  • 84,125
  • 8
  • 85
  • 148
1

Because sizeof is not a function, but an operator. It's argument has no side effects.

yyny
  • 1,623
  • 18
  • 20
  • 1
    Most of the time the operand of `sizeof` has no side effects. However, in `int n = 3; sizeof(int [n++]); printf("%d\n", n);`, `n` is changed, and “4” is printed. – Eric Postpischil Nov 15 '18 at 15:46