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 = 4, y, z;
        y = --x;
        z = x--;
        printf("%d%d%d", x, y, z);
    }

 

  • A.3 2 3
  • B.2 2 3
  • C.3 2 2
  • D.2 3 3

Answer: D

Correct answer: 2 3 3

Take the two statements in order. y = --x is a pre-decrement: x becomes 3 first and that new value is assigned, so y is 3.

z = x-- is a post-decrement: the current value 3 is assigned to z, and only then does x become 2. At the printf the variables are \( x = 2 \), \( y = 3 \), \( z = 3 \), printed in that order as 233. The whole question turns on which value the expression yields - the new one for a prefix operator, the old one for a postfix.

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

Post your comment

Please log in or register to post a comment.