Functions in C language
In this tutorial we'll learn last big thing in C language (and in any other programming language). After that we'll be able to create programs of any complexity. Of course we'll need to learn a lot, but we'll have a foundation.
First thing we need to understand: what is a function and why it's needed at all.
Function is a block of code that can be executed as many times as you need it. Usually programmers put in functions code that perform specific task.
To use function in C language first we need to define it.
Function definition in C language
Function definition consists of function header and function body. For example let's write the function that prints text:
Header of the function is the code before opening curly bracket. Identifier of the function (it's name): hello. Before the name there is a data type of return value, in our case it's void. In brackets we put arguments of the function, here it's void too.
Function body is the code in curly braces. This code is executed every time function is called.
After we defined the function, we can call it. When we printed the text with printf function that were calls of printf. Let's check more complete example:
In the main body (it's a function too by the way) we call function hello two times. When function is called processor executes it's body and then continue the execution. Call consists of two parts: function identifier and brackets. In brackets we can put arguments for function.
Function definition should be placed above any function calls. That's why definition of function hello I placed before function main. But there is one exception.
Function declaration in C programming language
Function declaration tells that the function with such name (and such arguments) exists, but it will appear later. Function declaration repeats function header but after it there is no function body. Here is example of previous code with function declaration:
Function parameters and arguments in C programming language