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

sizeof C中的函数类型

发布时间:2020-12-16 10:14:26 所属栏目:百科 来源:网络整理
导读:我有一些关于sizeof运算符的情况,它与函数类型一起使用. 案例1:[Live Demo] #include stdio.hchar func(){ printf("sizeof func = %zun",sizeof(func())); //Ok. Output : 1 return 0;}int main(void){ func();} sizeof(func())在C中有效吗? 案例2:[Live
我有一些关于sizeof运算符的情况,它与函数类型一起使用.

案例1:[Live Demo]

#include <stdio.h>

char func()
{
    printf("sizeof func = %zun",sizeof(func())); //Ok. Output : 1
    return 0;
}

int main(void)
{
    func();
}

sizeof(func())在C中有效吗?

案例2:[Live Demo]

printf("sizeof func = %zun",sizeof(&func())); // error

它不起作用.编译器给出错误.为什么?

案例3:[Live Demo]

printf("sizeof func = %zun",sizeof(&func)); //Ok. Output : 8

这里,sizeof(& func)是否等于指针的大小?

这里,案例3工作正常,其中案例2给出错误.为什么?

解决方法

在这个声明中

printf("sizeof func = %zun",sizeof(func()));

输出表达式的大小(未评估)func().由于函数的返回类型是char,因此表达式func()的类型为char,而sizeof(char)等于1.

来自C标准(6.5.3.4 sizeof和alignof运算符)

4 When sizeof is applied to an operand that has type char,unsigned
char,or signed char,(or a qualified version thereof) the result is
1….

在这个声明中

printf("sizeof func = %zun",sizeof(&func()));

尝试应用一元运算符&到一个临时对象,被评估为表达式func().您可能无法将操作符应用于临时对象.

从C标准(6.5.3.2地址和间接运算符)

1 The operand of the unary & operator shall be either a function
designator,the result of a [] or unary * operator,or an lvalue
that designates an object that is not a bit-field and is not declared
with the register storage-class specifier.

为了比较,请考虑以下程序

#include <stdio.h>

char * func()
{
    static char i = 0;

    printf("sizeof func = %zun",sizeof(&*func()));

    return &i;
}

int main(void)
{
    func();
}

在该程序中,该函数返回具有静态存储持续时间的左值i的指针.因此,应用一元运算符*,您将获得左值.所以你可以申请操作符&在这种情况下.

程序输出将是

sizeof func = 8

在这个声明中

printf("sizeof func = %zun",sizeof(&func));

对char(*)(void)类型的函数指针计算运算符sizeof.再次根据C标准的引用,操作符&可以应用于函数指示符.

考虑到函数定义应该是这样的

char func( void )
           ^^^^ 
{
    printf("sizeof func = %zun",sizeof(func())); //Ok. Output : 1
    return 0;
}

(编辑:李大同)

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

    推荐文章
      热点阅读