みなさん、C言語に於ける void 型をご存知でしょうか。
私は今日、入門者に void とはなにかを聞かれ、GNU C Extentionに足を掬われました。
私が今回言及したいのは、
関数定義の引数や戻り値がないことを示す void キーワードでは無い方の、
不完全型 (incomplete object type) の方の void です。
型 void とは? ¶
The
voidtype comprises an empty set of values; it is an incomplete object type that cannot be completed.
ISO/IEC 9899:201x Committee Draft — April 12, 2011 N1570 §6.2.5 Types 19 より引用
とあります。不完全型 (incomplete object type) であることがわかります。
不完全型 (Incomplete object type) とは? ¶
At various points within a translation unit an object type may be incomplete (lacking sufficient information to determine the size of objects of that type) or complete (having sufficient information).
ISO/IEC 9899:201x Committee Draft — April 12, 2011 N1570 §6.2.5 Types 1より引用
とあり、大事なのはサイズが不明 (Sizedでない) である部分ですね。
つまり、インスタンス化 void a やサイズ取得 sizeof(void) ができないという事になりそうです。
sizeof とは? ¶
念のため、 sizeof の方も確認しておきましょう。
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.
ISO/IEC 9899:201x Committee Draft — April 12, 2011 N1570 §6.5.3.4 Thesizeofand_Alignofoperators 1 より引用
いきなり、不完全型 (incomplete object type)に使うなと書かれています。
やはり sizeof(void) はだめなのでしょう。
実際にやってみた ¶
#include <stdio.h>
int main() {
printf("%zu\n", sizeof(void));
return 0;
}
このようなコードを書き、
$ gcc xx.c
$ ./a.out
1
$ clang xx.c
$ ./a.out
1
$
あれ?void は 不完全型 (incomplete object type) であり、サイズの取得はコンパイルエラーになるはずでは?
そしてなぜ1?
GNU C Extention - pointer-arith ¶
どうやら、GNU Cは void* を演算したいなどと余計なことを考えてしまったらしいのです。
しかしながら、ポインタ演算には当然ながら指されているObject Typeにサイズが必要ですね。
そこで仕方なく、voidのサイズを1ということにしてしまった様です。
関数ポインターも同様の事が行われているとのこと。
6.13.2 Arithmetic on void- and Function-Pointers ¶
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.
The option -Wpointer-arith requests a warning if these extensions are used.
https://gcc.gnu.org/onlinedocs/gcc/Pointer-Arith.html より引用
sizeof(void) をエラーにするには? ¶
--pedantic-errors をつけると良いということになっているらしいです。
$ gcc --pedantic-errors xx.c
xx.c: In function ‘main’:
xx.c:3:28: error: invalid application of ‘sizeof’ to a void type [-Wpointer-arith]
3 | printf("%zu\n", sizeof(void));
| ^~~~
$ clang --pedantic-errors xx.c
xx.c:3:21: error: invalid application of 'sizeof' to a void type [-Werror,-Wpointer-arith]
3 | printf("%zu\n", sizeof(void));
| ^ ~~~~~~
1 error generated.
$
おまけ: Instantiateは? ¶
Sizedってことは?と思い、Instantiateしようとしましたが、流石に駄目らしいです。
int main() { void a; }
$ gcc xxx.c
xxx.c: In function ‘main’:
xxx.c:1:19: error: variable or field ‘a’ declared void
1 | int main() { void a; }
| ^
$ clang xxx.c
xxx.c:1:19: error: variable has incomplete type 'void'
1 | int main() { void a; }
| ^
1 error generated.
$
おまけ: 実験環境 ¶
- Arch Linux
- clang version 23.1.3
- gcc (GCC) 16.2.1 20260810