Skip to content
Related Articles

Related Articles

C | Storage Classes and Type Qualifiers | Question 9
  • Difficulty Level : Easy
  • Last Updated : 09 Feb, 2013

Output?




#include <stdio.h>
int fun()
{
  static int num = 16;
  return num--;
}
  
int main()
{
  for(fun(); fun(); fun())
    printf("%d ", fun());
  return 0;
}


(A) Infinite loop
(B) 13 10 7 4 1
(C) 14 11 8 5 2
(D) 15 12 8 5 2


Answer: (C)

Explanation: Since num is static in fun(), the old value of num is preserved for subsequent functions calls. Also, since the statement return num– is postfix, it returns the old value of num, and updates the value for next function call.

fun() called first time: num = 16 // for loop initialization done;


In test condition, compiler checks for non zero value

fun() called again : num = 15

printf("%d \n", fun());:num=14 ->printed

Increment/decrement condition check

fun(); called again : num = 13

----------------

fun() called second time: num: 13 

In test condition,compiler checks for non zero value

fun() called again : num = 12

printf("%d \n", fun());:num=11 ->printed

fun(); called again : num = 10

--------

fun() called second time : num = 10 

In test condition,compiler checks for non zero value

fun() called again : num = 9

printf("%d \n", fun());:num=8 ->printed

fun(); called again   : num = 7

--------------------------------

fun() called second time: num = 7

In test condition,compiler checks for non zero value

fun() called again : num = 6

printf("%d \n", fun());:num=5 ->printed

fun(); called again   : num = 4

-----------

fun() called second time: num: 4 

In test condition,compiler checks for non zero value

fun() called again : num = 3

printf("%d \n", fun());:num=2 ->printed

fun(); called again   : num = 1

----------

fun() called second time: num: 1 

In test condition,compiler checks for non zero value

fun() called again : num = 0 => STOP 


Quiz of this Question

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :