Question
Option 4 : Undefined behaviour — `r` refers to a destroyed local variable / Undefined behaviour — `r` नष्ट हो चुके local variable को संदर्भित करता है
Detailed Solution
सही उत्तर Undefined behaviour — `r` refers to a destroyed local variable / Undefined behaviour — `r` नष्ट हो चुके local variable को संदर्भित करता है है।
Question:
What is the behaviour of the following C++ code? `int& f() { int x = 10; return x; } int main() { int& r = f(); r = 20; cout << r; }` / निम्नलिखित C++ कोड का व्यवहार क्या है? `int& f() { int x = 10; return x; } int main() { int& r = f(); r = 20; cout << r; }`
Correct Answer: Undefined behaviour — `r` refers to a destroyed local variable / Undefined behaviour — `r` नष्ट हो चुके local variable को संदर्भित करता है
`f` returns a reference to its local `x`, which is destroyed when `f` returns, so `r` dangles and any use is undefined behaviour — it may print 20 today and crash tomorrow. The trap is assuming the assignment through `r` is safe because it "worked" once. / `f` अपने local `x` का reference लौटाता है, जो `f` के लौटते ही नष्ट हो जाता है, अतः `r` dangling है और उसका कोई भी उपयोग undefined behaviour है — आज 20 छप सकता है, कल क्रैश हो सकता है। जाल यह मानना है कि `r` से assignment सुरक्षित है क्योंकि एक बार "चल गया" था।