C語言沒有引用,只有指針
作者:佚名
我想說的已經在題目說明的很清楚了,C語言是沒有引用的,引用是在C++里面才存在的神級操作。
這個問題是昨晚上有同學在知識星球提問,但是因為前兩天一直在出差,比較累,沒認真回答,今天打球回來,就把這個事情解決了。
我想說的已經在題目說明的很清楚了,C語言是沒有引用的,引用是在C++里面才存在的神級操作。
所以,什么是引用呢?
說白了引用&就是給已經存在的某個變量新建了一個名字,如果程序對引用別名做了某些操作,其實就是對原目標的改動。
C ++ 引用實例
- #include<stdio.h>
- #include<stdlib.h>
- void exchange(int &x, int &y)
- {
- int t;
- t = x;
- x = y;
- y = t;
- }
- int main()
- {
- int a, b;
- scanf("%d %d", &a, &b);
- exchange(a, b);
- printf("%d %d\n",a,b);
- getchar();
- return 0;
- }
程序輸出
- 12 34
- 34 12
- --------------------------------
- Process exited after 3.121 seconds with return value 0
- 請按任意鍵繼續(xù). . .
C語言有什么呢?
C語言是萬變不離其宗的指針,引用在C++里面出現(xiàn)后,讓編程變得非常友好,你看上面的操作,看起來就非常明了。
不過我們也可以使用指針來完成上面的操作
實例代碼
- 12 34
- 34 12
- --------------------------------
- Process exited after 3.121 seconds with return value 0
- 請按任意鍵繼續(xù). . .
程序輸出
- 12 56
- 56 12
- --------------------------------
- Process exited after 2.477 seconds with return value 0
- 請按任意鍵繼續(xù). . .
留一個討論題目
討論下下面的程序輸出什么?
- #include<stdio.h>
- #include<stdlib.h>
- void exchange(int *x, int *y)
- {
- int *t = x;
- *x = *y;
- *y = *t;
- }
- int main()
- {
- int a, b;
- scanf("%d %d", &a, &b);
- exchange(&a, &b);
- printf("%d %d\n",a,b);
- getchar();
- return 0;
- }
責任編輯:龐桂玉
來源:
C語言與C++編程