Is void a data type in C?

一曲冷凌霜 提交于 2019-12-17 08:29:41

问题


Is void a data type in the C programming language? If so, what type of values can it store? If we have int, float, char, etc., to store values, why is void needed? And what is the range of void?


回答1:


Void is considered a data type (for organizational purposes), but it is basically a keyword to use as a placeholder where you would put a data type, to represent "no data".

Hence, you can declare a routine which does not return a value as:

void MyRoutine();

But, you cannot declare a variable like this:

void bad_variable;

However, when used as a pointer, then it has a different meaning:

void* vague_pointer;

This declares a pointer, but without specifying which data type it is pointing to.




回答2:


Yes, void is a type. Whether it's a data type depends on how you define that term; the C standard doesn't.

The standard does define the term "object type". In C99 and earlier; void is not an object type; in C11, it is. In all versions of the standard, void is an incomplete type. What changed in C11 is that incomplete types are now a subset of object types; this is just a change in terminology. (The other kind of type is a function type.)

C99 6.2.6 paragraph 19 says:

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

The C11 standard changes the wording slightly:

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

This reflects C11's change in the definition of "object type" to include incomplete types; it doesn't really change anything about the nature of type void.

The void keyword can also be used in some other contexts:

  • As the only parameter type in a function prototype, as in int func(void), it indicates that the function has no parameters. (C++ uses empty parentheses for this, but they mean something else in C.)

  • As the return type of a function, as in void func(int n), it indicates that the function returns no result.

  • void* is a pointer type that doesn't specify what it points to.

In principle, all of these uses refer to the type void, but you can also think of them as just special syntax that happens to use the same keyword.




回答3:


The C Standard says that void is an incomplete type that cannot be completed (unlike other incomplete types that can be completed). This means you cannot apply the sizeof operator to void, but you can have a pointer to an incomplete type.



来源:https://stackoverflow.com/questions/3487689/is-void-a-data-type-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!