#include <iostream>
#include<stdlib.h>
using namespace std;
class test{
public:
test(int a):i(a){
}
int display();
private:
int i;
};
int test::display(){
i;
}
int main() {
test obj(10);
cout<<obj.display();
return 0;
}
In above case some random value is printed. But when I changed function declaration as :
int& display();
and definition as :
int& test::display(){
i;
}
It displayed correct value i.e. 10 I don't know why?
This is undefined behavior, so anything is possible - including a possibility when your code "works" as expected. Your compiler should have issued a warning about this - it is important to treat such warnings as errors, and fix all reported problems before testing your code.
Compilers use stack or CPU registers to return values from functions. When a return
is missing, no data is placed in the space of the return value. However, the data that you planned to return may already be in a register or on the stack in just the right place, so the calling code exhibits the behavior you expect. It remains undefined, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With