Return value of a function

I'm a newbie to C++ programming. I'm learning about function. There is a case that I'm wondering about return value of a function. E.g the following function:

1
2
3
4
  int foo(int a, int i){
     if (i!=0) --a;
     else return a*2;
  }


I call the following functions in main() function:
cout << foo(10,0)<<endl;
cout << foo(10,3)<<endl;

The printed results are:
20
9

The first case is clearly understandable 'cause i==0.
I do not understand why the second case returns 9.

I am very appreciate if someone can help me clarify the issue.
You get garbage because the function doesn't return anything when i is not zero.

Did you forget the return keyword? if (i!=0) return --a;
I honestly forgot the return keyword and thought that the call foo(10,3) doesn't have any value. But when I run the script, it does. My question is why in this case (i=3), there is no keyword return but cout<<foo(10,3)<<endl prints 9.
I don't know why you get the value 9. It's probably just what happens to be stored at the location in memory where the return value was supposed to be written to. It's nothing you should rely on. This is what's called undefined behaviour. The program breaks the rules of the language so anything is allowed to happen.
Last edited on
I've tried to change the function to recursion type as following [still not return keyword for if]:

1
2
3
4
 int foo(int a, int i){
     if (i!=0) a=foo(a,i-1)+1;
     else return a*2;
  }


Get printed result for:
cout << foo(10,0)<<endl;
cout << foo(10,3)<<endl;
are:
20
23

Can you explain it to me?
Last edited on
No I can't explain because the behaviour of the program is not defined. When I run your program I get a different output, and it changes depending on what optimization flags I pass to the compiler. If you want to find out exactly what is going on you'll have to study the assembly produced by the compiler, but that is probably not meaningful. Just write a correct program and you will get the correct output.
Last edited on
Topic archived. No new replies allowed.