有時看到如下的代碼:
/*****************************/ #include<stdio.h> #include<string.h> #include <stdlib.h> void test(){printf("123456\n");} int main(intargc,char*argv[]) {printf("0x%x\n",test); printf("0x%x\n",&test);} [[emailprotected]pht]# ./a.out 0x80483280x8048328

按照&運算子本來的意義,它要求其運算元是一個物件,但函式名不是物件(函式是一個物件),本來&test是非法的,但很久以前有些編譯器已經允許這樣做, c/c++標準的制定者出于物件的概念已經有所發展的緣故,也承認了&test的合法性,
如果你也想成為程式員,想要快速掌握編程,趕緊關注小編加入學習企鵝圈子吧!
里面有資深專業軟體開發工程師,在線解答你的所有疑惑~編程語言入門“so easy”
資料包含:編程入門、游戲編程、課程設計等,
免費學習書籍:

免費學習資料:

因此,對于test和&test你應該這樣理解,test是函式的首地址,它的型別是void (),&test表示一個指向函式test這個物件的地址, 它的型別是void (*)(),因此test和&test所代表的地址值是一樣的,但型別不一樣,
test是一個函式,&test運算式的值是一個指標! 跟此問題類似的還有對一個陣列名取地址,
int a[100]; printf("%p\n", a); printf("%p\n", &a[0]); 列印值一樣, 但是陣列名a,指向的是具有100個int型別的組數;
&a[0]指向的是元素a[0], 即他們的值相同,但指向的型別不同, 標準在其rationale中解釋了這個問題,摘錄如下:
6.5.3.2 Address and indirection operators Some implementations have not allowed the & operator to be applied to an array or a function. (The construct was permitted in early versions of C, then later made optional.) The C89 Language Committee endorsed the construct since it is unambiguous, and since data abstraction is enhanced by allowing the important & operator to apply uniformly to any addressable entity.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/241695.html
標籤:C
