in Programming in C edited by
25,247 views
103 votes
103 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.
in Programming in C edited by
by
25.2k views

4 Comments

Val value in bar function is always 3

Am I right!
0
0
Question:- Why there is abnormal termination in bar()

It will also fill stack by calling bar(1) multiple times????
0
0

Usefull comment

bar 3 calls bar 2..bar 2 calls bar 1..bar 1 calls bar 0...now comes the concept..

return 0 transfers the control to while(1>0) condition and we know that this condition in while loop means while loop will execute infinitely..

Please go through the previous question(GATE2017-1-35 )for clarity about the return statement...

0
0

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

2 Comments

U say bar 0 means condition false which condition is false in your achknoledgement ......
0
0
It's the while condition. while(0>0) here.
0
0
5 votes
5 votes

May Be It Works :

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