Functions :: The Basics
- Why should we make functions in our programs when we can just do it all under main? Weiss (pg. 77) has a very good analogy that I'll borrow :) Think for a minute about high-end stereo systems. These stereo systems do not come in an all-in-one package, but rather come in separate components: pre-amplifier, amplifier, equalizer, receiver, cd player, tape deck, and speakers. The same concept applies to programming. Your programs become modularized and much more readable if they are broken down into components.
- This type of programming is known as top-down programming, because we first analyze what needs to be broken down into components. Functions allow us to create top-down modular programs.
- Each function consists of a name, a return type, and a possible parameter list. This abstract definition of a function is known as it's interface. Here are some sample function interfaces:
char *strdup(char *s)
The first function header takes in a pointer to a string and outputs a char pointer. The second header takes in two integers and returns an int. The last header doesn't return anything nor take in parameters.
int add_two_ints(int x, int y)
void useless(void) - Some programmers like to separate returns from their function names to facilitate easier readability and searchability. This is just a matter of taste. For example:
int
add_two_ints(int x, int y) - A function can return a single value to its caller in a statement using the keyword
return. The return value must be the same type as the return type specified in the function's interface.
Tags:
Functions :: The Basics