|
C++ Programming Tutorials
Functions with no
type. The use of void.
If you remember the syntax of a function declaration:
type name ( argument1, argument2 ...) statement
you will see that the declaration begins with a type, that is the type
of the function itself (i.e., the type of the datum that will be
returned by the function with the return statement). 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. In this case we should
use the void type specifier for the function. This is a special
specifier that indicates absence of type.
// void function example
#include <iostream>
using namespace std;
void printmessage ()
{
cout << "I'm a function!";
}
int main ()
{
printmessage ();
return 0;
} |
I'm a function!
|
void can also be used in the function's parameter list to
explicitly specify that we want the function to take no actual parameters when
it is called. For example, function printmessage could have been declared as:
void printmessage (void)
{
cout << "I'm a function!";
} |
Although it is optional to specify void in the parameter
list. In C++, a parameter list can simply be left blank if we want a function
with no parameters.
What you must always remember is that the format for calling a function includes
specifying its name and enclosing its parameters between parentheses. The
non-existence of parameters does not exempt us from the obligation to write the
parentheses. For that reason the call to printmessage is:
The parentheses clearly indicate that this is a call to a
function and not the name of a variable or some other C++ statement. The
following call would have been incorrect:
NEXT >>
Functions (II)
Have a Question ?
post your questions here. It
will be answered as soon as possible.
Check
C Aptitude Questions
for more C Aptitude Interview Questions with Answers
Check
C Interview Questions
for more C Interview Questions with Answers.
|