I am trying the following code. I haven't written "return" in the function, and I expect after executing the "cout" line, it prints "0" which proves that the function works well, but it always prints "m"'s value. What's the problem?
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
int increase (int k)
{
k=k+1;
}
int main ()
{
int m=10;
std :: cout << increase (m);
}
I'm not sure but I think it's because you cout << increase (m);
and I've also had bugs with the return 0 and I just type return 0; after the program. hope this helps and sorry if it didn't.
You need to add return k; at the end of increase(). Right now the return value is whatever random number happens to be on the stack.
What exactly do you want increase() to do? Should it actually increase the variable, or just return 1+k? If you want it to actually increase the variable then you need to pass k by reference (int increase (int &k)
Why did you expect the result to be 0? I would assume the compiler see the function being called does nothing so it optimizes and ignores the call to the function. Hence it calling m. Throw and output statement or something that actually does something and the output will be different than m. It will have an undefined output.
As people have said, this behavior should be undefined. cl.exe won't even try to compile it. My guess is that your program just happens to be expecting the return value from the increase function to be in the same place as where it pushed the argument to your function.
Thank you all for your comments. This program always prints m's value, at least with the provided compiler and code blocks. I had another similar code with arrays which it returns zero. Why is the behavior different to individual numbers and arrays?