void / void * declaration behaviour

174 Views Asked by At

program 1:

int main()
{
    void v=8;
    printf("v=%d\n",v);
}

program 2:

int main()
{
    void *v=8;
    printf("*v=%u\n",*v);
    printf("v=%u\n",v);
}

compilation error on program 1:

**error**: variable or field ‘v’ declared void void v=0;

compilation errr on program 2:

**error**:invalid use of void expression printf("%d\n",*v);

Could anybody knows the behaviour of void and void* in the above program codes?

2

There are 2 best solutions below

2
On

A void * is just a pointer that Points to someting you don't know. So you can initialize ist. Even a void* isn't very useful, but it is a pointer and can be casted to a pointer of a specific type.

A void variable is "something you don't know" and so it can never be initialized and can not be declared.

2
On

void has two uses:

  • Either as part of function declarations, stating that a function returns nothing, or takes no parameters.

  • Or as the generic pointer type void*, which can be used to convert to/from any other pointer to type, without an explicit cast.

C11 6.2.5/19 states that:

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

This means that you cannot define variable as void nor dereference a void*.

This is stated more clearly in 6.3.2.2

6.3.2.2 void

The (nonexistent) value of a void expression (an expression that has type void) shall not be used in any way, and implicit or explicit conversions (except to void) shall not be applied to such an expression. If an expression of any other type is evaluated as a void expression, its value or designator is discarded. (A void expression is evaluated for its side effects.)