C + + value types and reference type passing examples

Source: Internet
Author: User

Win32test.cpp: Defines the entry point of the console application. #include "stdafx.h" void swap_point (int * &a, int * &b) {int temp = *a; *a = *b;*b = temp;//Destroy caller pointer//a = NULL; b = NULL;p rintf ("swap_point:[0x%x", [0x%x] \ r \ n ", &a, &b);} void Swap (int * A, int * b) {int temp = *a; *a = *b;*b = temp;//Destroy caller pointer invalid//a = NULL;//b = null;p rintf ("swap:[0x%x], [ 0x%x] \ r \ n ", &a, &b);} void swap (int & A, int & b) {int temp = A; a = b; b = temp;p rintf ("swap:[0x%x], [0x%x] \ r \ n", &a, &b) ;} int _tmain (int argc, _tchar* argv[]) {/*int *ptr[3];for (int i = 0; i < 3; i++) {Ptr[i] = new int[5]; for (int l = 0; l < 5; l++) {Ptr[i][l] = i * l;p rintf ("%d *%d =%d \ r \ n", I, L, Ptr[i][l]);}}  *//*int (*PTR) [3];p tr = (int (*) [3]) malloc (sizeof (int *) * 5); for (int i = 0; i < 5; i++) {(*ptr) [0] = 1; (*ptr) [1] = 2; (*ptr) [2] = 3;ptr++;} The initial y[9][9 Array char = {0};*/int a = 3; int b = 4;//The pointer is passed by value (cannot modify the value of the caller pointer variable), call swap, pointer variable Ptra, PTRB is passed by "value", where swap in T * A, int * b Copy Ptra, PTRB pointer variable int * Ptra = &a; int * ptrb = &b; Swap (Ptra, PTRB);p rintf ("a =%d [0x%x], B =%d[0x%x ], Ptra = [0x%x], PTRB = [0x%x] \ r \ n ", A, &a, B, &b, &ptra, &AMP;PTRB);//pointer passed by reference (can modify the value of the caller pointer variable), call SW Ap_point, pointer variable Ptra, PTRB is passed by "reference", where swap is int * A, int * b is ptra, PTRB pointer variable swap_point (PTRA, PTRB);p rintf ("a = %d [0x%x], B =%d[0x%x], Ptra = [0x%x], PTRB = [0x%x] \ r \ n ", A, &a, B, &b, &ptra, &AMP;PTRB);//By reference Pass a = 3; b = 4; swap (A, b);p rintf ("a =%d [0x%x], b =%d[0x%x] \ r \ n", A, &a, B, &b); System ("pause"); return 0;}

C + + value types and reference type passing examples

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.