Cannot compile with void variable in C

test.c

int main () { void a; return 0; } 

I use gcc to compile, but this gives me an error:

error: variable or field 'a' declared void

From what I read here , I thought I could declare a void variable without a problem.

+4
source share
4 answers

As your link says:

A variable that is itself declared invalid (for example, my_variable above) is useless; it cannot be assigned a value that cannot be distinguished from another type, in fact, cannot be used in any way.

This means that although it is syntactically correct, a void declaration is not useful, so GCC might consider this an error. Even if it compiles, you cannot do anything with the variable, so I think your question is simply related to testing this behavior.

In fact, void is useful when we talk about pointers ( void* ), since it allows you to declare a generic pointer without specifying a type.

+9
source

No, but you can declare a pointer to void: void * . A void * can contain any object pointer.

void * only the preservation of object pointers (i.e. data) is guaranteed

[a]

it does not carry over to convert the function pointer to void * type

+5
source

Although the book states that void a; is a valid expression, I do not believe that it has ever been a standard. That being said, the first edition of the book was from 1987, so it can also be ported from older implementations of GCC.

+1
source

void *x; is a valid statement.

void x; is not a valid operator.

A function returning a pointer to void is also true.

Why is this so?

When a variable is declared in a function, the compiler must allocate memory space for the variable. But when the variable is of type void, the compiler does not know how many bytes are allocated for this variable. So this will not work for the compiler. However, a pointer to void is different. The pointer can be of type void, which can be read as int or double or float or short or char while reading. In this case, the compiler performs explicit type conversion or automatic type advancement.

eg.

 int function_A( void *x ) { int *p = (int *)x; return *p; } double function_B( void *x ) { double *p = (double *)x; return *p; } 

Important Note: C does not allow the direct dereferencing type of the void pointer. I mean, you cannot do this:

 double function_B( void *x ) { return (double)*x; } 

Conceptually, this makes sense. But C does not allow this.

0
source

All Articles