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 a = 5, b = -7, c = 0, d;
        d = ++a && ++b || ++c;
        printf("\n%d%d%d%d", a, b, c, d);
    }

 

  • A.6 -6 0 0
  • B.6 -5 0 1
  • C.-6 -6 0 1
  • D.6 -6 0 1

Answer: D

Correct answer: 6 -6 0 1

Work left to right with the short-circuit rules. ++a makes a 6, which is non-zero and therefore true; ++b makes b −6, also non-zero and true, so the && yields 1.

The || then has a true left operand, so it short-circuits: ++c is never evaluated and c stays 0. The result d is 1. The trap is −6, which is true because it is non-zero - truth in C is non-zero, not positive.

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

Post your comment

Please log in or register to post a comment.