Skip to content
Related Articles

Related Articles

Improve Article
GATE | GATE-CS-2017 (Set 1) | Question 39
  • Last Updated : 21 Feb, 2017

Consider the C functions foo and bar given below:

int foo(int val)
{
    int x = 0;
    while (val > 0)
    {
        x = x + foo(val--);
    }
    return val;
}

int bar(int val)
{
    int x = 0;
    while (val > 0)
    {
        x = x + bar(val-1);
    }
    return val;
}

Invocations of foo(3) and bar(3) will result in:

(A) Return of 6 and 6 respectively
(B) Infinite loop and abnormal termination respectively
(C) Abnomal termination and infinite loop respectively
(D) Both terminating abnormally


Answer: (C)

Explanation: In the function foo every time in the while foo is called with the value 3 because val is passed with post decrement operator so the value 3 is passed and val is decremented later. Every time the function is called a new variable is created as the passed variable is passed by value, with the value 3. So the function will close abruptly without returning any value.

In the function bar, in the while loop value the value of val variable is not decrementing, it remains 3 only. Bar function in the while loop is called with val-1 i.e 2 but value of val is not decremented, so it will result in infinite loop.

Quiz of this Question

Attention reader! Don’t stop learning now. Learn all GATE CS concepts with Free Live Classes on our youtube channel.

My Personal Notes arrow_drop_up
Recommended Articles
Page :