Return creates a temporary variable before execution to save the value to be returned,
Returned value: returns a copy value, which has been eliminated.
Return pointer: When returned, the original pointer space will be eliminated. if not used by other programs, the original pointer space will be correctly returned. If released and used by other programs, the values in this space may be modified, and the return value may be incorrect;
What values are still valid except for functions:
1. Global variables;
2. static variable. Because static is equivalent to a global variable, it will not be recycled by the system.
Example:
[Cpp]
# Inlcude <iostream. h>
Int & sum (int, int );
Int main (void ){
Int x = 5, y = 10;
Printf ("% d \ n", sum (x, y ));
Return 0;
}
Int & sum (int a, int B ){
Static int x;
X = a + B;
Return x;
}
3.int * p = new int;
When p is returned, a copy of p will be generated, which itself is no longer valid, but www.2cto.com in the copy of p
It is valid because it contains the new address. (It is valid if the address is not manually released
)
Example:
[Cpp]
Int * small (int x, int y ){
Int * p = new int;
Return p;
}
4. If a reference is passed and the return is also a reference, it can be returned correctly because it is defined outside the function.
[Cpp]
# Include <iostream>
Int & max (int &, int &);
Int main (){
Int x = 15, y = 10;
Printf ("% d \ n", max (x, y ));
Return 0;
}
Int & max (int & a, int & B ){
If (a> B)
Return;
Else
Return B;
}
5. If a variable is passed and the returned result is also a variable, it can also be returned correctly. However, when it creates a copy and returns it, if it is not received in time, it will disappear.
Note: Never return pointers and references to local variables. errors may occur;
From like7xiaoben