偶然發如今C中sizeof(void)是合法的,因而,對它的做用產生了疑問。查閱資料在GNU文檔中發現以下解釋:html
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.express
測試代碼以下:app
#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)是不合法的,編譯錯誤以下:this
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
Referencesspa
1.http://gcc.gnu.org/onlinedocs/gcc-4.4.6/gcc/Pointer-Arith.htmlcode