Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is void *a = &a legal?

Tags:

c++

Consider the following C++ code:

void* a = &a; 

Why doesn't the compiler complain for using an undeclared identifier?

Also, what does the compiler consider the variable a to be? Is it a pointer to a void object or is it a pointer to a void* pointer?

like image 835
user2681063 Avatar asked Aug 14 '13 06:08

user2681063


People also ask

What is void * used for?

void (C++)When used as a function return type, the void keyword specifies that the function doesn't return a value. When used for a function's parameter list, void specifies that the function takes no parameters.

What type is a void * in C?

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

Can you free a void * in C?

yes it is safe.

What does void * func () mean?

Void functions, also called nonvalue-returning functions, are used just like value-returning functions except void return types do not return a value when the function is executed. The void function accomplishes its task and then returns control to the caller. The void function call is a stand-alone statement.


2 Answers

The scope of declaration of variables in C++ can be pretty surprising:

void* a =               &a;          ^~~~~~~~~~~~~~~~~           a declared as `void*` from here on 

Therefore, &a is void** but since any pointer type is implicitly convertible to void*...

like image 169
Matthieu M. Avatar answered Sep 23 '22 23:09

Matthieu M.


It is equivalent to

void* a; a = &a; 

Therefore, a has been declared. So a gets the address of a written in a. So it is a pointer to a void pointer. (You did not define any objects yet.)

like image 42
Stasik Avatar answered Sep 25 '22 23:09

Stasik