C allows you to create your own functions. Functions accept parameters and return a result. They let us simplify our programs into sections that can be called by other sections. Let's have a look at a simple example:
Now remember we said a functions returns a value. We put void because our function doesn't. if we expected it to return an int value, we put int. if a char, we put char, etc. We then declare the name of the function and the code to be executed goes between the curly braces.header();
Is how we call the function, we must use the () in the call to tell the compiler we're calling a function. Our program uses no parameters and returns no result, it is a very simple function. But it shows you the structure and how to declare one. We could now use this in a program.
Functions allow us to break up the program, if we wanted to print out the info about our program over and over in differen parts of a program, it's easier to use a function and just call it.
Returning a Value
We can return values from a function, take a look below:
Now our function returns a result, it returns an integer. We add 2 and 3 together, assign the result to the_sum and then return it.So we define the return type as int:
Then we write the function that adds to numbers together. Then we open the main() function of our program and assign the result returned from our function to a variable:sum = our_sum();
That's returning a result, the result the function returned was assigned to sum.
No Comments for this page.