小议C语言中的void类型

标准对void类型的定义

在C99标准文档中,对void类型的定义如下(ISO 9899:2011 6.2.5/19):

The void type comprises an empty set of values; it is an incomplete type that cannot be completed.

这里面很重要的一点是:void类型是不完整类型。对于不理解什么是不完整类型的童鞋请参考这篇文章《C语言的不完整类型和前置声明》。

明白了定义后,接下来让我们小议一下跟void类型相关的小问题。


sizeof(void)等于多少?

先使用不同的编译器试试结果如何吧(注意:使用的是C语言编译方式)。

Microsoft Visual C++ 2005/2008给的结果为0.

gcc version 4.9.2给出的结果为1.

clang version 3.6.0-2ubuntu1给出的结果也是1.

好了,对于这样的结果是不是很意外呢? 首先sizeof(void)这样的语句合法吗? 如何合法,怎么不同的编译器给出的结果不同呢?

一起来看看标准是怎么说的吧,如下(ISO 9899:2011 6.5.3.4/1):

The sizeof operator shall not be applied to an expression that has function type or an incomplete type, to the parenthesized name of such a type, or to an expression that designates a bit-field member.

很明显,标准的意思就是sizeof(void)这样的语句是不合法的,或者更严格地说,这样的语句是未定义的,也就是编译器实现相关的。那么为什么以上编译器都没有报错呢? 对于微软的编译器我不了解,对于gcc来说,这是gcc的扩展语法,请参阅《Arithmetic on void- and Function-Pointers》。如何使gcc遵循标准呢? 我们可以增加编译选项-std=c99 -pedantic来使gcc发出警告:“warning: invalid application of ‘sizeof’ to a void type [-Wpointer-arith]”,甚至可以指定-pedantic-errors来使gcc直接报错:“error: invalid application of ‘sizeof’ to a void type [-Wpointer-arith]”。clang也可以使用同样的编译参数来完成遵循标准。

By the way,谁要是写出这样的代码我打死谁!!!

参考链接:

Why does sizeof(void) == 1?

What is the size of void?


指针void *

1. sizeof(void *)的值为多少?

关于sizeof(void *)的值为多少就没有什么好争议的了,它的值是编译的目标平台相关的,如果目标平台是32位的,则sizeof(void *)等于4;如果是64位的,等于8;如果16位的,等于2。

2.void *与其它指针类型之间的转化

这点比较重要,也是很多人有疑惑的地方,并且在C语言和C++语言中他们的规则稍微有一些区别。

(1)void *向其它类型指针的转化

我爱你

(2)其它类型的指针向viod *的转化

我爱你



参考阅读:

void及void指针含义的深刻解析

Void and void pointer

C Corner Cases (and Funny Things)

Malloc and Casting

Do I cast the result of malloc?

Should I explicitly cast malloc()'s return value?

Why does this code segfault on 64-bit architecture but work fine on 32-bit?

Segfault on IA-64, but not on IA-32

Why does some code carefully cast the values returned by malloc to the pointer type being allocated?

Specifically, what's dangerous about casting the result of malloc?

malloc的强制类型转换

What's wrong with casting malloc's return value?

对malloc的返回值应该如何转型

对malloc的返回值应该如何转型

why is casting malloc a bad thing?

Pointer Conversions

void pointers: difference between C and C++

《 C标准里没有规定void *到其它指针的转换都是implicit的吧?


很具有争议的一篇文章

MEM02-C. Immediately cast the result of a memory allocation function call into a pointer to the allocated type


Using void* in Generic C Programming may be Inefficient

Don’t use casts


Why aren't `void *`'s implicitly cast in C++?


void* and casts, in C and C++

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值