edited by
25,332 views
104 votes
104 votes

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:

  1. Return of $6$ and $6$ respectively.
  2. Infinite loop and abnormal termination respectively.
  3. Abnormal termination and infinite loop respectively.
  4. Both terminating abnormally.
edited by

7 Answers

6 votes
6 votes
In bar function,val-1 decreases val by 1..so bar 3 calls bar 2..bar 2 calls bar 1..bar 1 calls bar 0..bar 0 means condition(while 0>0) is false therefore return 0..

Now, return 0 ..return statement definition is it should terminate the current function bar 0 and transfer the control to the calling function bar 1 which is while(1>0)...

while(1>0) means infinite loop...so ans is C

Also,In foo function,val-- means post decrement operator.so val is decremented only in the next statement.so foo(val--) means foo3 calls foo3..foo3 calls foo3..foo3 calls foo3 repeatedly causing abnormal termination of the program.

Please go through the previous question(GATE2017-1-35 )for clarity about the return statement..
reshown by
0 votes
0 votes
while(val>0)
{
x = x + foo(val--);
}
In this case foo(val--) is same as foo(val) & val-- ;
Because the recursive function call is made without changing the passing argument and there is no Base condition which can stop it.
It goes on calling with the same value ‘val’ & the system will run out of memory and hits the segmentation fault or will be terminated abnormally.
The loop will not make any difference here.
while(val>0)
{
x = x + bar(val-1);
}
bar(3) calls bar(2)
bar(2) calls bar(1)
bar(1) calls bar(0) ⇾ Here bar(0) will return 0.
bar(1) calls bar(0)
bar(1) calls bar(0)……..
This will continue.
Here is a problem of infinite loop but not abrupt termination.
Some compilers will forcefully preempt the execution.
Answer:

Related questions

68 votes
68 votes
5 answers
3