In C and C++ ‘void‘ means no type and so we cannot use void as a data type or declare a variable of void type.
Since void means no type it there is no literals of such type.This makes void type as a suitable return type when no value is return by the function.For instance,
cout << “This function returns nothing” ;
return ; /* return nothing or you can also remove this return ; statement t will mean the same*/
int main( )
func( ) ;
return 0 ;
This is one of the uses of void type-suitable for return type when no value is returned-in C++.
There is an exception to the use of void as a type.Although declaring a variable for a void is not allowed we can declare a pointers of a void type.
void rd ; ///Error
The advantage of using void pointer is that a void pointer can point to the address of any data type.But we cannot access the value which it points to.
void *ip ;
ip=&i ; ///Works fine
cout<< *ip ; /* error:cannot access the value of i */
Accessing void pointer
If we want to access the value of another variable which the void pointer points to then we have to cast the void pointer to that type.
void *ip=&i ;
int *iv=static_cast<int *>(ip) ; ///Casting ip to int type
cout<< *iv ;
So ,the disadvantage of using void pointer is that we have to know the exact data type of the variable to cast it.Beware! if we cast the void pointer to some other type it will introduce a bug in your code.
string st=*static_cast<string *>(ip) ;// casting to string type
cout<< st ; //undefined