sizeof(void)有什么用

本文探讨了C语言中sizeof(void)的合法性及其返回值为1的原因,通过引用GNU文档解释了这一现象,并对比了C++中对此用法的不同处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

偶然发现在C中sizeof(void)是合法的,于是,对它的作用产生了疑问。查阅资料在GNU文档中发现如下解释:

In GNU C, addition and subtraction operations are supported on pointers to void and on pointers to functions. This is done by treating the size of a void or of a function as 1. A consequence of this is that sizeof is also allowed on void and on function types, and returns 1.

测试代码如下:

#include <stdio.h>

int main(int argc, char* argv[]) {
  printf("sizeof(void): %lu\n", sizeof(void));
  printf("sizeof(function): %lu\n", sizeof(main));
  return 0;
}

 C语言中输出如下:

sizeof(void): 1
sizeof(function): 1

C++中sizeof(void)是不合法的,编译错误如下:

void_size.c: In function ‘int main(int, char**)’:
void_size.c:15: error: invalid application of ‘sizeof’ to a void type
void_size.c:16: error: ISO C++ forbids applying ‘sizeof’ to an expression of function type

 

References

1.http://gcc.gnu.org/onlinedocs/gcc-4.4.6/gcc/Pointer-Arith.html

 

转载于:https://www.cnblogs.com/hellogc/p/3374756.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值