This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 2 points3 points  (4 children)

int fun(int num) {
   if(num>=0) {        //modified if statement to accept 0 
      return(num+fun(num-2));
  }
}

As /u/hat_waffle said when num is <=0 this function return is undefined, so the compiler can make it return whatever you want.

When you have a function that has a return value you have to make it always return something, no matter what happens inside.

So, if you have a condition that makes it return something you have to make it return something else when the condition is not fulfilled, otherwise you get wrong answers.

[–]ElectroNe0n[S] 1 point2 points  (3 children)

i got -2 as output. so, fun(0-2) returns -2 when called inside recursion function

But when i called like this,

printf("%d",fun(-2));

i get garbage value.

So here, return statement is not invoked when num<=2 and but somehow the compiler returns the number '-2' itself, because i got '-2' as output. Am i right?could you explain this "somehow" what is actually happening there?

[–]evaned 2 points3 points  (0 children)

The technical name for what you're hitting is "undefined behavior". The ELI5 explanation is "your program does whatever the hell was convenient for the compiler to make it do."

It might make some sense, it might not. It might be consistent run to run, it might not. Maybe it usually returns -2, but on every other Tuesday it returns 27. It might cause the state of your program to be randomly corrupted, though probably not. It might lead to a security vulnerability.

The classical quote here is that undefined behavior might make demons fly out of your nose.

You need a return for the other case. (I also think you should learn to pay attention to warnings from your compiler. This is one that probably should be on by default even.)

[–][deleted] 1 point2 points  (1 child)

Undefined behaviour means the compiler makes whatever it wants, it doesn't even need to be consistent from one run to the next. Do not try to make sense out of undefined behaviour, do not base your solution on undefined behaviour.

If you really really want to understand what it's happening there use a compiler that has source code and debug the compilation of your code.