[Conventional] comparison of several methods for passing parameters by function

Source: Internet
Author: User
    • Specify two methods for passing parameters by function

      Pass-by-value and pass-by-Reference)

    • Specify the data transfer methods for C and C ++

      C language only supports pass-by-value, while C ++ implements pass-by-value and pass-by-reference)

    • Implementation demo of C and C ++

C implementation

 
# Include <stdio. h> # include <stdlib. h> void swap (int * a, int * B); int main (INT argc, char * argv []) {int A = 1, B = 2; int * P1 = & A, * P2 = & B; printf ("before swap! P1 = [% x], P2 = [% x] \ n ", P1, P2); swap (P1, P2); printf (" after swap! P1 = [% x], P2 = [% x] \ n ", P1, P2); getch (); Return 0;} void swap (int *, int * B) {int TMP; TMP = * A; * A = * B; * B = TMP; return ;}

Description: after running the command, you will find that the values of P1 and P2 have not changed before and after swap (P1, P2) is called.

C ++ implementation

# Include <stdio. h> # include <stdlib. h> void swap (Int & A, Int & B); int main (INT argc, char * argv []) {int A = 1, B = 2; printf ("before swap! A = [% x], B = [% x] \ n ", & A, & B); swap (a, B); printf (" after swap! A = [% x], B = [% x] \ n ", & A, & B); getchar (); Return 0;} void swap (Int &, int & B) {int TMP; TMP = A; A = B; B = TMP; return ;}

Description: In this function, swap implements operations on the addresses of Two integer variables. In this way, it must be passed by reference. At this time, the value of A and B in SWAp will also be reflected in the main function.

 

Conclusion: It is actually very simple to say so much. So to prove what?

1. When passing values, the called function will not change its own parameters.

2. During reference transfer, the called function may change the passed parameters and reflect the situation to the main function. If you do not want to change it, you need to add the const before the parameter to control it.

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.