Question

1.
2.
3.
4.
Answer (Detailed Solution Below)

Option 4 : Undefined behaviour — `r` refers to a destroyed local variable / Undefined behaviour — `r` नष्ट हो चुके local variable को संदर्भित करता है

Advertisement

Detailed Solution

सही उत्तर Undefined behaviour — `r` refers to a destroyed local variable / Undefined behaviour — `r` नष्ट हो चुके local variable को संदर्भित करता है है।

Key Points
Helpful?
PrepSnapprepsnap.in • Part -A

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; }`

1.
Prints 10 / 10 प्रिंट करता है
2.
Prints 20 reliably / विश्वसनीय रूप से 20 प्रिंट करता है
3.
Compilation error — cannot bind reference to return value / कंपाइलेशन त्रुटि — return value से reference bind नहीं हो सकता
4.
Undefined behaviour — `r` refers to a destroyed local variable / Undefined behaviour — `r` नष्ट हो चुके local variable को संदर्भित करता है

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 सुरक्षित है क्योंकि एक बार "चल गया" था।

Downloaded from PrepSnap (prepsnap.in)