Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the following C code?

#include <stdio.h>
    void main()
    {
        int x = 97;
        int y = sizeof(x++);
        printf("x is %d", x);
    }

 

  • A.x is 97
  • B.x is 98
  • C.x is 99
  • D.Run time error

Answer: A

Correct answer: x is 97

sizeof does not evaluate its operand. The compiler needs only the type of the expression to determine its size, and that is known at compile time, so x++ is never executed.

Consequently y receives the size of an int and x remains 97. This is a genuine and easily missed rule: any side effect written inside sizeof - an increment, an assignment, even a function call - simply does not happen. The one exception is a variable-length array type, whose size must be computed at run time.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.