Monday, September 29, 2008

Functions with no types. The use of void.

If you remember the syntax of a function declaration:
type name
( argument1, argument2 ...) statement

you will see that it is obligatory that this declaration begins with a
type, that is the type of the data that will be returned by the function with the return instruction. But what if we want to return no value?
Imagine that we want to make a function just to show a message on the screen. We do not need it to return any value, moreover, we do not need it to receive any parameters. For these cases, the
void type was devised in the C language. Take a look at:

#include <iostream.h>
void dummyfunction (void)
{
cout << "I'm a function!";
}
void main ()

{
dummyfunction ();
getch();
}

The following is the result:
I'm a function!
Although in C++ it is not necessary to specify
void, its use is considered suitable to signify that it is a function without parameters or arguments and not something else.

What you must always be aware of is that the format for calling a function includes specifing its name and enclosing the arguments between parenthesis. The non-existence of arguments does not exempt us from the obligation to use parenthesis. For that reason the call to dummyfunction is
dummyfunction ();

This clearly indicates that it is a call to a function and not the name of a variable or anything else.

Source : Cplusplus.com

No comments: