Monday 22 April 2013

void type

Functions can be declared as returning void, meaning they do not return a value.
void can also be used in the parameter list of a function. C++ differs from ANSI C on the
meaning of a function declaration with a null argument list, e.g. fred();, in ANSI C this
means that the function can take any number of arguments, in C++ it means that this
function does not take any parameters, i.e. C++'s fred(); is equivalent to ANSI C's
fred(void);. C++ accepts fred(void); for compatibility with ANSI C.
The generic pointer type is void * as it is in ANSI C, but again there is a difference. C++
will allow the assignment of any pointer to a void * variable or parameter, but the reverse
always requires a cast. In ANSI C, both assignments are permitted without a cast.
void fred();
// A function that takes no parameters and
// does not return a value.
void *harry();
// A function that takes no parameters and
// returns a pointer to void
void *jim(void *);
// A function that takes a void * parameter
// and returns a pointer to void
int main()
{
int i;
int *ptr2int;
float *ptr2float;
i = fred();
// illegal, fred does not return a value
fred(i);
// illegal, fred takes no parameters
ptr2int = harry();
// illegal, cast required for (void *) to (int *)
ptr2int = (int *)harry();
ptr2float = (float *)harry();
// OK, casts used
ptr2int = (int *)jim(ptr2float);
// OK, no cast needed for pointer to anything to
// void *
return 0;
}

No comments:

Post a Comment