加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C语言函数名以及取地址的区别和联系

发布时间:2020-12-16 09:11:26 所属栏目:百科 来源:网络整理
导读:有时看到如下的代码:? /*****************************/#include stdio.h#include string.h#include stdlib.hvoid test(){ printf("123456n");}int main(int argc,char *argv[]){ printf("0x%xn",test); printf("0x%xn",test);}[[email?protected] pht]#

有时看到如下的代码:?

/*****************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void test()
{
    printf("123456n");
}

int main(int argc,char *argv[])
{
    printf("0x%xn",test);
    printf("0x%xn",&test);
}

[[email?protected] pht]# ./a.out 
0x8048328
0x8048328

按照&运算符本来的意义,它要求其操作数是一个对象,但函数名不是对象(函数是一个对象),本来&test是非法的,但很久以前有些编译器已经允许这样做,?c/c++标准的制定者出于对象的概念已经有所发展的缘故,也承认了&test的合法性。?因此,对于test和&test你应该这样理解,test是函数的首地址,它的类型是void (),&test表示一个指向函数test这个对象的地址,?它的类型是void (*)(),因此test和&test所代表的地址值是一样的,但类型不一样。test是一个函数,&test表达式的值是一个指针!?跟此问题类似的还有对一个数组名取地址。?int a[100];?printf("%pn",a);?printf("%pn",&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.?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读