C++-傳值與傳引用的區別,引用

來源:互聯網
上載者:User

C++-傳值與傳引用的區別,引用

//值傳遞與引用傳遞的區別#include <iostream>#include <iomanip>using namespace std;void fiddle(int in1, int &in2){in1 = in1 + 100;in2 = in2 + 100;cout << "The values are ";cout << setw(5) << in1;cout << setw(5) << in2 << endl;}int main(){int v1 = 7, v2 = 12;cout << "The values are:";cout << setw(5) << v1;cout << setw(5) << v2 << endl;fiddle(v1, v2);cout << "The values are:";cout << setw(5) << v1;cout << setw(5) << v2 << endl;system("pause");return 0;}


運行結果:

7 12

107 112

7 112 


可以得出結論,如果穿引用將會改變變數最初的值,而如果傳值在函數中使用後並不會改變其原來的值


c!!!!!!!!!!

1.

#include <stdio.h>
#define N 20
void fun( int a[],int n)
{ int i,j,t,p;
for (j=0;j<n-1;j++)
{ p=j;/*這裡缺少分號*/
for( i=j;i<n;i++)
if(a[i]<a[p]) p=i; /*這裡應該是p=i而不是p=j*/
t=a[p];a[p]=a[j];a[j]=t;
}
}
main()
{ int a[N]={9,6,8,3,-1},i,m=5;
printf("排序前的資料:");
for(i=0;i<m;i++) printf("%d",a[i]); printf("\n");
fun(a,m);/*這裡應該調用fun()函數進行排序*/
printf("排序後的資料:");
for(i=0;i<m;i++) printf("%d",a[i]); printf("\n");
}

2.

int fun(int n) /*缺少傳回值類型及參數類型*/
{int c;
if (n==1) /*應該是n==1而不是n=1*/
c=10;
else
c=fun(n-1)+2;
return(c);
}
main()
{int n;
scanf("%d",&n);
printf("%d",fun(n));
}
 
c+=c-=c*c

從右往左看
假設C=2
則最右端的C1*C1=4
c1-=c1*c1 等價 c2=c1-c1*c1 此時c=2-4=-2
c1+=c2 等價 c3=c1+c2 此時c3=2+(-2)=0
整個式子中c的值是不停變化的,分別為2,-2,0
當C=5時,結果c=-15

上述過程中c1、c2、c3分別代表c值變化的三個過程。

該結果我經編程驗證。
建議用進階的IDE,用進階語言寫短代碼,並Debug,發現C變化的細節。
這個問題跟語言沒有關係,因為幾乎所有語言都要用到變數。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.