sizeof(void)有什么用

偶然发现在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

 

posted @ 2013-10-17 19:46  离小木  阅读(2112)  评论(0编辑  收藏  举报