0

I have observed that if I don’t return any value from an empty function with an int return type is 1. But in the below case it is showing 4 3 2 as o/p(is this the value of the static variable si getting printed here? if I print si I will get o/p as 2 3 4, in the reverse of what I get now. is there something to do with the function's stack push and pop here in this case?). Also I observed that if I use float as return type then it prints nan nan nan as o/p. Is this behavior compiler dependant (I have tried with both gcc and devcpp, observed the same)? What is actually going on here? Please share your thoughts on this.

#include<iostream>
using namespace std;


int f(int i){
     static int si = i;
     si = si + i;
     ///return si;
}

int main(){
    cout<<f(1)<<" "<<f(1)<<" "<<f(1);
    //cout<<" "<<f(1);    //if I uncomment this line then the o/p is: 4 3 2 5, it looks like it's printing the value of si.
}

It looks like the behavior of cout causing the reverse printing of static variable si's value?

Renuka
  • 217
  • 1
  • 6

1 Answers1

7

It is undefined behaviour. You have to return something from a non-void function*

From § 6.6.3 The return statement [stmt.return]

Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

* The main() function has an implicit return 0 so it is not necessary to explicitly return. This is a special case.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • If it's undefined then why I am getting the same o/p from different compilers for every execution of same piece of the code as above? Does it mean there is something defined which is of `type undefined`? – Renuka Apr 13 '14 at 13:05
  • 3
    @Renuka It is undefined behaviour. Anything can happen. – juanchopanza Apr 13 '14 at 13:06
  • okay thanks juanchopanza :) – Renuka Apr 13 '14 at 13:08
  • @Renuka I get `4 3 2` as well. Maybe it is the value of si laying around in some register, and the function calls are being executed from right to left.. But why does any of this matter? – Leonardo Apr 13 '14 at 13:10
  • 1
    @Leonardo, here I am trying to understand more about the behavior which I have observed from the above piece of code even if it’s undefined. – Renuka Apr 13 '14 at 15:33
  • *Undefined behavior* means the implementation can do anything in response to it and still be compliant with the standard. **Anything**. It could erase your hard drive instead of printing `4 3 2`, and that would be OK as far as the standard is concerned. – David Hammen Apr 15 '14 at 07:31