GATE / CS ARCHIVE

GATE CSE 2021 SET 1 / QUESTION 37

GATE CSE 2021 Set 1 Q37

Programming in C · Expressions, Operators & Types · Full GATE CSE 2021 Set 1 paper

GATE 2021 Set 1, Q37 2 marks · MCQ
Report issue

Expressions, Operators & Types

Question 37, GATE 2021: What happens in this ANSI C program? #include <stdio.h>
int main(void){ int i,j,count; count=0; i=0; for(j=-3;j<=3;j++){ if((j>=0)&&(i++)) count=count+j; } count=count+i; printf("%d",count); return 0; }
A fails compilation; B compiles and prints 10; C compiles and prints 8; D compiles and prints 13.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Step through it (35 steps)

For j=−3,−2,−1 the left operand of && is false, so i++ is not evaluated. At j=0 the old i=0 makes the condition false, but increments i to 1. At j=1, 2, 3 the old i is nonzero, adding 1+2+3=6 while i reaches 4. The final addition gives count=6+4=10. Thus B. Short-circuiting and postincrement order are defined by C.

A compact trace (j, i after condition, count after body) is (−3,0,0),(−2,0,0),(−1,0,0),(0,1,0),(1,2,1),(2,3,3),(3,4,6). Postincrement yields the old value as the expression result, then changes i. The logical AND operator sequences and short-circuits its operands, so the first three iterations do not increment i at all. The final statement adds the final i=4 once, obtaining 10 without undefined unsequenced modifications.

Original paper, page 31 · Answer key