Section 12.1 Single Functions
You have already seen the use of a function in C, namely the
main() function! We don’t tend to think of
main() as a function but it is indeed one.
Functions allow you to group a bunch of statements together that can be called upon to execute at any point in your code. Depending on the type of function you write, you can pass information to the function and it can return information back to you.
Here is a first example of a function in C:
If you cannot see this codecast, please click here .
Aside: Video Description.
Writing functions
Calling functions
NEW SYNTAX: the following is the function prototype for a function that takes in two integers, x and y, and returns one integer (this return integer could be anything but we are going to return the sum of x and y).
int sum (int x, int y);
NEW SYNTAX: the body (that is, the set of instructions to be executed when calling the function) of the function "sum" comes after the main function ends. This is called the function definition and it starts out the same way as the prototype, except for the semi-colon ; at the end of the prototype. After that initial line come curly brackets {}, which enclose the (potentially) multi-line body of the function.
int sum (int x, int y){ };
c = sum(a,b)