Wednesday, September 29, 2010

Functions of Type void

One of void's uses is to explicitly declare functions that do not return values. This
prevents their use in any expression and helps avert accidental misuse. For example,
the function print_vertical() prints its string argument vertically down the side of
the screen. Since it returns no value, it is declared as void.
void print_vertical(char *str)
{
while(*str)
printf("%c\n", *str++);
}
Here is an example that uses print_vertical() .
#include <stdio.h>
void print_vertical(char *str); /* prototype */

int main(int argc, char *argv[])
{
if(argc > 1) print_vertical(argv[1]);
return 0;
}
void print_vertical(char *str)
{
while(*str)
printf("%c\n", *str++);
}
One last point: Early versions of C did not define the void keyword. Thus, in
early C programs, functions that did not return values simply defaulted to type int.
Therefore, don't be surprised to see many examples of this in older code.

No comments:

Post a Comment