幾種交換兩個數函數(swap函數)的寫法和解析

來源:互聯網
上載者:User
#include <iostream>using namespace std;/*值傳遞,局部變數a和b的值確實在調用swap0時變化了,當結束時,他們繩命周期結束*/void swap0(int a, int b){int tem = a;a = b;b = a;}/*沒有初始化指標就開始用,該函數是有問題的*/void swap1(int *a, int *b){int *tem;/*注意tem沒有分配記憶體*/*tem = *a;*a = *b;*b = *tem;}/*函數內只是指標的變化,指標的值沒有變化*/void swap2(int *a, int *b){int *tem;tem = a;a = b;b = tem;}/*指標傳遞實現兩個數的交換*/void swap3(int *a, int *b){int tem;tem = *a;*a = *b;*b = tem;}/*指標傳遞實現兩個數的交換*/void swap4(int &a, int &b){int tem;tem = a;a = b;b = tem;}int main(){int num1 = 1;int num2 = 2;//swap0(num1, num2);//swap1(&num1, &num2);//swap2(&num1, &num2);//swap3(&num1, &num2);    swap4(num1, num2);cout << num1 << endl << num2 << endl;return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.