This is my tutorial on functions. They really speed up your programs.
A function is basically a piece of code that can be executed by typing a single line,
so you don't need to re-write it every time. Here's what a basic function looks like:
void name() {
printf("Yawuh!");
}
Make sure you write your code outside int main(). (which, by the way, is a function)
void is what the function returns - in this case nothing.
We'll get back to that.
The parentheses( the "(" and ")" ) are where the arguments go.
They're also known as parameters. Arguments can be used to modify the function. For example,
if your function looks like this:
void name(int num) {
printf("%d", num);
}
And you call it like this:
name(5);
The output will be:
5
And now for prototypes. If you want, you can put a declaration at the beginning
of the program, and define the function later, like this;
void name(int);
...some code, possible the main() function...
void name(int x) {
printf("%d", x);
}
It's generally considered good form to use prototypes.
Also, if you're using a project on your compiler, you can include a file with the
prototypes and link them both with a file with the declarations. DWKS and KAWK know
all about this because of their graphics engine: e-mail or private message them
if you have a question about it.
And now to returning. Remember that? Returning is what the function's value will be.
If
int sample() {
return 5;
}
Then
if(sample()==5) printf("YAY!");
will print YAY! Remember: don't do this too much, because it actually calls the function.
It could slow it down.
void functions can return as well, but they can't return a value: just typing
return;
at any point during the function terminates it.
Of course, you could use
int isequal(int num, int n2) {
if(num==n2) return 1;
else return 0;
}
Then,
if(isequal(5, x)==1) printf("He entered 5");
else printf("He didn't enter 5.");
Get it?
That's all they're really is to functions. Be sure to check out Kawk's tutorial on C
in general. If you have any more questions, sign up to our forum.
-Stormchaser