Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accidently I forgot to return value from function but when I returned reference in function declaration it worked.Why?

Tags:

c++

#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?

like image 572
Abhinav Chauhan Avatar asked Dec 17 '14 17:12

Abhinav Chauhan


1 Answers

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.

like image 97
Sergey Kalinichenko Avatar answered Nov 11 '22 06:11

Sergey Kalinichenko