C++ | References | Question 5

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
using namespace std;
  
int &fun()
{
    int x = 10;
    return x;
}
int main()
{
    fun() = 30;
    cout << fun();
    return 0;
}

chevron_right


(A) May cause runtime error
(B) May cause compiler error
(C) Always works fine.
(D) 0


Answer: (A)

Explanation: Since we return reference to a local variable, the memory location becomes invalid after function call is over. Hence it may result in segmentation fault runtime error.

Quiz of this Question



My Personal Notes arrow_drop_up


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.