Programming in C

(Barry) #1

8Working with Functions


8 Working with Functions

BEHIND ALL WELL-WRITTEN PROGRAMSin the C programming language lies the same
fundamental element—the function.You’ve used functions in every program that you’ve
encountered so far.The printfand scanfroutines are examples of functions. Indeed,
each and every program also used a function called main. So you might ask, what is all
the fuss about? The truth is that the program function provides the mechanism for pro-
ducing programs that are easy to write, read, understand, debug, modify, and maintain.
Obviously, anything that can accomplish all of these things is worthy of a bit of fanfare.

Defining a Function


First, you must understand what a function is, and then you can proceed to find out how
it can be most effectively used in the development of programs. Go back to the very first
program that you wrote (Program 3.1), which displayed the phrase “Programming is
fun.” at the terminal:
#include <stdio.h>

int main (void)
{
printf ("Programming is fun.\n");

return 0;
}
Here is a function called printMessagethat does the same thing:
void printMessage (void)
{
printf ("Programming is fun.\n");
}

TEAM FLY

Free download pdf