GATE / CS ARCHIVE

GATE CSE 2015 SET 3 / QUESTION 42

GATE CSE 2015 Set 3 Q42

Programming in C · Scope, Lifetime & Storage Classes · Full GATE CSE 2015 Set 3 paper

GATE 2015 Set 3, Q42 2 marks · NAT
Report issue

Scope, Lifetime & Storage Classes

Question 42, GATE 2015: Determine the output of this C program, using the standard function-call sequencing model:
#include <stdio.h>
int f1(void); int f2(void); int f3(void);
int x=10;
int main() { int x=1; x += f1()+f2()+f3()+f2(); printf("%d",x); return 0; }
int f1() { int x=25; x++; return x; }
int f2() { static int x=50; x++; return x; }
int f3() { x *= 10; return x; }
Tap to enlarge
Answer & solution

Official answer: 230

1. There are three distinct variables named x: global x, main’s automatic x, and f2’s persistent static x; f1 additionally creates its own automatic x on entry. Name lookup selects the nearest declaration, so f3 alone modifies the global. The two f2 returns may exchange evaluation order, but their sum stays 103.

2. Main’s local x starts 1. f1 returns 26 from its own automatic x; the two f2 calls return 51 and 52 from one static x in either order; f3 multiplies global 10 by 10 and returns 100. Sum1+26+51+52+100=230. Function executions are indeterminately sequenced, so unspecified operand order does not change the sum or cause overlapping unsequenced increments.

Original paper, page 67 · Answer key