By chance, I forgot to return the value from the function, but when I returned the link in the function declaration, it worked. Why?

#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 the above case, a random value is printed. But when I changed the function declaration as:

 int& display(); 

and definition as:

 int& test::display(){ i; } 

The correct value is displayed, i.e. 10 I do not know why?

+5
source share
1 answer

This behavior is undefined, so anything is possible - including the possibility that your code "works" as expected. Your compiler should have warned about this - it is important to take into account warnings such as errors, and fix any problems encountered before testing your code.

Compilers use stack or processor registers to return values ​​from functions. When a return absent, the data does not fit into the return value space. However, the data that you planned to return may already be in the register or on the stack only in the right place, so the call code demonstrates the behavior that you expect. It remains undefined, however.

+7
source

Source: https://habr.com/ru/post/1209375/


All Articles