a function consists of three parts:
- input values
- output values (usually only one)
- some code to produce the output value.
in c this looks like this:
Code:
int sum(int a,b) {
return a+b;
}
this would be a mathematical function.
a function can also group a task in one central location:
Code:
char ask_driver() {
char tmp;
printf("Are there guests?");
do {
scanf("%c",tmp);
} while ( (tmp!='y') && (tmp!='n') )
return tmp;
}
this function takes no input parameters "()" and returns one character (weŽll use "y" for yes and "n" for no.). it does not allow you to type anything else.
functions are handy if you need to re-use code. if you type code twice and you correct a mistake in the first, 99% youŽll forget about the second time this code appears. say your bus company rises prices.
and your code will look more readable.
compare this:
Code:
int main() {
while (true) {
printf("how many passengers");
do {
scanf("%d",&passengers);
} while (passengers<=1)
printf("how many adults");
do {
scanf("%d",&adults);
} while (adults<=0)
printf("how many children");
do {
scanf("%d",&children);
} while (adults<=0)
}
}
compared to:
Code:
void ask(char *question, *fmt;void *answer; int min) {
do {
printf(question);
scanf(*fmt, answer);
} while (*(int*)answer<=min);
}
int main() {
while (true) {
ask("How many passengers","%d",&passengers,1)
ask("How many adults","%d",&adults,0)
ask("How many children","%d",&children,0)
}
}
isnŽt the second one much easier to understand?
disclaimer: no responsibility. this code is untested and probably needs modification before it compiles. sorry for the long post ;)