0

Why the codes differ?

why these codes produce different output just by adding cout.. https://code.sololearn.com/cu5qYEX8Y9Hp/?ref=app https://code.sololearn.com/cX6Pp9wBrYTW/?ref=app

11th Mar 2018, 9:52 PM
Shubham
Shubham - avatar
5 Respostas
+ 3
C++ may use a placeholder for the variable name when declared within a function. If you change the variable i to e or some other name within the g() function the result may still be. 1 2 You can think of this as an anonymous pointer to a memory location for a certain type held in a register for functions. The name given within the function is merely for the programmer to recognize its use within the function body. Once the function body has ended the register frees up the pointer for use within another function. This essentially has to do with the placeholder pointer pointing to the memory location for a variable of a given type, the timing of the retrieval of the value from that memory location. If you changed the scope of i outside of the functions then you would have the expected result. There is no guarantee of the values that will be received when you write the code the way it currently is,since the local variable(s) are/may be destroyed once the function has reached the closing curly brace. Results may have been deferent given a slower machine, in which the value held in the memory location of i has already been changed prior to it being retreived elsewhere in your program.
11th Mar 2018, 10:27 PM
ChaoticDawg
ChaoticDawg - avatar
+ 3
with my logic now, how can a pointer is can be point to a destroyed variable inside function? i will understand if we use static variable inside function. really confusing
11th Mar 2018, 10:30 PM
Kevin AS
Kevin AS - avatar
+ 2
There might be any reason. a points to a variable which is out of scope (DELETED) when you pass it to cout. You have no guarantee that deleted variables don't change. And it seems like when cout is used, something gets added to the stack where our deleted variable was. I said it seems like, this mustn't be right. Just don't use deleted variables.
11th Mar 2018, 10:08 PM
Timon Paßlick
+ 1
A local variable is destroyed when its scope ends. But as the pointer just holds the address, it doesn't notice.
11th Mar 2018, 10:34 PM
Timon Paßlick
0
@chaotic thanks.that seems logical to me .
12th Mar 2018, 3:21 AM
Shubham
Shubham - avatar