+ 13

What is the output of this code ?

plz explain the output of this code thanks in advance https://code.sololearn.com/cbly2U5snaHT/?ref=app

24th Dec 2017, 4:35 PM
Randeep Singh
Randeep Singh - avatar
5 Answers
+ 9
I have seen this que in our challenges 😊😊😊... there r two types of que .... 1st one is the one u have coded in which fun is assigned value 30 and then called by & operator and returns value 10.... so output is 10.. 2nd one is like this :- int &fun(){ static int x=10; return x; } int main(){ fun()=30; cout<<fun(); return 0; } outputs:---30 The difference between them is just that in 2nd one the x is made static... if we don't use static, var. is reinitialized.... u can understand rest.... 😊😊😊 I hope this helps
24th Dec 2017, 5:05 PM
🌛DT🌜
🌛DT🌜 - avatar
+ 2
#include <iostream> using namespace std; int & fun(); int main() { fun()=30; // Assigns 30 to the deleted variable. You have no guarantee it will stay 30 until you use it again. Setting it to 30 could also corrupt a variable of another process. cout<<fun(); // Gets again a deleted 10 (again a disaster) and puts it into the output stream. No guarantee it will be 10 when the library processes it to write it to the screen. return 0; //unnecessary } int & fun(){ // Returns x by referene. This is a disaster: When x goes out of scope in line 12, it is deleted. But you're still using it. int x=10; return x; }
24th Dec 2017, 4:47 PM
Timon Paßlick
+ 2
while calling func() function with reference. the value of &func() becomes 30.and we have declared static keyword with the variable x assigned to 10.then we are returing x.so value of x becomes 30.then the cout statement is displayed.
22nd May 2021, 6:12 AM
Sridevi R
0
With a static variable, there is also no disaster. ( : But the output of version 1 is just probably 10 - it's undefined.
24th Dec 2017, 7:22 PM
Timon Paßlick
0
ans is 17
23rd Jun 2020, 1:53 PM
ROSHINI S
ROSHINI S - avatar