Create your own game
eng   рус

Functions in C language

Previous tutorial: Arrays and strings in C language
Next tutorial: Header files and multi-file sources in C language

In progress

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:

void hello(void) { printf("Hello!!!\n"); }

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.

Function call

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:

void hello(void) { printf("Hello!!!\n"); } int main (void) { hello(); hello(); return 0; }

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:

void hello(void); int main (void) { hello(); hello(); return 0; } void hello(void) { printf("Hello!!!\n"); }

Function parameters and arguments in C programming language


In this tutorial we learn about the functions in C programming language. All tutorials that we learnt so far (except, I may say, pointers) covers materials that can be easily transferred to any other programming language (Java, Python, C++, PHP, JavaScript). Any language has ideas of conditions, loops, functions. The base we've obtained will help us in our next tutorials. In next tutorials we'll practice to improve our skills.


No comments yet