简体   繁体   中英

Can't compile with void variable in C

test.c

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

I use gcc to compile but it gives me an error:

error: variable or field 'a' declared void

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

As your link states:

A variable that is itself declared void (such as my_variable above) is useless; it cannot be assigned a value, cannot be cast to another type, in fact, cannot be used in any way.

This means that although syntactically correct, a void declaration is not useful to anything, this is why GCC could consider it an error. Even if it would compile, you won't be able to do anything with the variable, so I guess your question is just related to testing this behavior.

In fact void is useful just when we're talking about pointers ( void* ) since it allows you to declare a generic pointer without specifying the type.

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

void *'s are only guaranteed to hold object (ie data) pointers

[but]

it is not portable to convert a function pointer to type void *

Although the book states that void a; is a valid statement, I don't believe it has ever been standards compliant. That being said, the first edition of the book was from 1987, so it could also be carry-over from older implementations of GCC.

void *x; is a valid statement.

void x; is not a valid statement.

A function that returns a pointer to void is also valid.

Why is this so?

When a variable is declared in a function, the compiler has to allocate a memory space for a variable. But when a variable is of type void, the compiler doesn't know how many bytes to allocate for this variable. So this will not work for the compiler. However, the pointer to void is different. A pointer can be of type void which can be read as an int or a double or a float or a short or a char at the time of reading. In this case, explicit typecasting required or automatic type promotion is done by the compiler.

eg

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

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

An important note: C does not allow direct typecast of dereference of void pointer. What I mean by this is that you cannot do this:

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

Conceptually, this makes perfect sense. But C doesn't allow this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM