Home > Backend Development > C++ > What is the Size of \'void\' in C?

What is the Size of \'void\' in C?

Mary-Kate Olsen
Release: 2024-11-19 17:25:03
Original
838 people have browsed it

What is the Size of

Question: Understanding the Undefined Size of "void"

In C programming, the keyword "void" represents an absence of type. This raises the question: what is the size of "void"?

Answer:

The type "void" has no defined size in C. It is not a valid type for objects or pointers, so attempting to use it as such would lead to a compilation error. Specifically, the statement:

void n;
Copy after login

is invalid because it tries to declare a variable of a void type, which is not allowed.

Extension: Allocation and Pointer Arithmetic with "void" Pointers

Although "void" has no size, it can be used as a type for pointers. However, such pointers do not point to any specific type or size of data.

The statement:

void *p = malloc(sizeof(void));
Copy after login

results in a compile-time error because trying to allocate memory for a "void" type is nonsensical. The function malloc requires a valid data type to allocate memory for.

In GCC, the expression sizeof(void) surprisingly evaluates to 1. While this might seem like it assigns a size to "void", it is merely an implementation detail that should not be relied upon.

Additionally, the pointer arithmetic p on a "void" pointer is undefined and should not be used. This is because the type of data pointed to by p is unknown, making it impossible to determine what incrementing the pointer would mean.

The above is the detailed content of What is the Size of \'void\' in C?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template