C ++ language beginner-return value

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.