C Functions Complete Tutorial

In this section, we will learn what the Functions are and how to use them in C.

C Function Analogy:

The definition of the word `Function` According to the Longman dictionary is: “the purpose that something has, or the job that someone or something does.”

When you go to a restaurant, probably the first person you’ll see is the Host that he/she will greet you and show you a table to seat. This is the function of a Host to `greet and show a place for customers to seat`.

Then you have restaurant’s server (waiter and waitress) that he/ she will take your orders and probably give it to the chief in order to make them ready. So the function of waiter/ waitress is to `take orders and bring food to customers`.

Of course there are other people working in a restaurant like a dishwasher that he/ she should wash the dishes and sometimes even the floor. So we can say the functions of a dishwasher are `washing the dishes and the floors`.

Each person who works in this restaurant has a name. For example, Ellen is the Host, Jack is the Restaurant’s server and Bob is the dishwasher.

Let’s go a little deeper:

The waiter/ waitress, in order to function correctly first and foremost, should be called by the customer (she can’t just go on their table over and over to see if they need anything). After the waitress is called, she needs input (orders) from the customer to proceed to its function! But she can’t just receive any type of input! For example, the customer of a restaurant can’t order a Car!!! So there are some limits on the types of orders that the customer can give. These limits become clear when the waitress puts a menu in front of the customer!

After the waitress took the correct inputs, she’ll call another person (let’s say the chief) and give her order to that chief. The waitress should be careful as well because the chief also can’t take any types of order!

During this time, the customer can’t proceed to eat because she is waiting for her order to be received.

Also, the waitress is waiting for the food so we can say that her function is not completed yet.

Now the ordered food is ready and the chief `returns` the actual food to the waitress and waitress passes this food to the customer.

The customer can now proceed to eat and the function of the waitress and the chief are completed at this time.

Note: the customer had one function here and that was eating. She started by calling a waitress which is equal to start someone else’s function, and then waited for that function to be finished. The function of the waitress finished when she returned the food to the customer. At this point, the customer can proceed and run the rest of her function (eating).

What is Function in C?

In the world of C programming, we have the concept of functions as well!

One function can call another function (like the way customer called the waitress), one function can pass inputs to another function (just like the way the customer passed order to the waitress), the caller function can wait until the called function finished its work and the called function can return a value to the caller function (just like the way the waitress passed the actual food to the customer).

Note: In C programming, we name the function that starts a communication the `caller` function and the target function as the `called` or `callee` function. In our example, the caller function is the customer and the called or callee function is the waitress.

Also, a function can be `called/ callee ` and `caller ` at the same time! In our example, the waitress has these adjectives! The customer `called` the waitress and so now she becomes the `called/ callee` function. Then she calls the chief and passes the order and so now she is in the position of the `caller` function.

Function Creation in C:

There are two steps in order to create a function in C:

  1. Function Declaration
  2. Function Definition

1- Declaration of a Function in C:

  1. Let’s back to the restaurant; the declared function of the waitress is to take an order from any customer in the restaurant and return food relative to the order she took.

Declaring is about what the inputs of a function are and what the output is. At this stage, we don’t care about the logics that should be defined within the body of that function. All we care is the `name of the function` and `the type` of `inputs` and `output` of the function.

In C programming, we call function declaration as `prototype` of that function.

Notes:

  • The usual place of declaring a function is above the `main` function. But that doesn’t mean we can’t put the prototype inside a function. The point is that, before a function is called, there should be a prototype already declared somewhere that the compiler knows about.
  • We can skip the declaration of a function. In this case, the function should be defined above the `main` function.

There are two structures by which we can declare the prototype of a function in C:

Data_type function_name();

Data_type function_name(data_type parameter_1, double parameter_2, double parameter_N );

Note: If the function that we are going to build does not need inputs in order to function correctly, then we can use the first structure, otherwise, if inputs are necessary, the second structure should be used instead.

Data_type: Here, we set the type of output that is expected from the function.

The types can be those that are covered in the data-type section as well as enum, union and structure types.

Note: if the function does not return any output, we replace the `data_type` with the keyword `void` which means empty or basically a signal to the compiler that after running the function, there won’t be any returning value.

Example:

void sum();

Function Identifier in C(function_name):

Any function should have a unique name in order to differentiate functions from each other and be able to call them. This name is known as the identifier of the function.

Rules for creating a name for a function are the same as those rules that apply to the variable names.

C Functions Open and close parentheses ()

There are two reasons why we use parentheses here:

First= using parentheses helps us and the compilers to differentiate a function from a variable! Think about it, how could we figure out which name is for a function and which name is for a variable if there weren’t any parentheses?

Second= if a function also takes inputs, we declare the type of each input within the parentheses when we declare a function. This way, we know what type of arguments (inputs) we should pass to the target function when that function is getting called.

Note: we also use parentheses in order to call a function which is covered later in this section.

Function Parameters in C:

As mentioned before, a function can take inputs from its caller. These input values should be stored in variables in order to be able to use those values in a function at later times. We store these values in a variable that is known as function-parameter.

These parameters are declared within the parentheses that come after the name of a function.

Note: multiple parameter should be separated from each other using comma `,`.

C Function Prototype Semicolon `;`:

When a function is declared (prototyped), we end that function declaration with a semicolon `; `.

Example: function declaration in C

int sum(int valueOne, int valueTwo );

In the example above, we’ve `declared` or `prototyped` a function that outputs a value of type `int`, the name of the function is `sum` and it takes `two inputs of type int`.

Each input of the function is called the `parameter` of that function, we separate them via comma `,` and each parameter is considered the local variable of that function.

So in the example above, we’ve declared two parameters for the `sum` function with the names `valueOne` and `valueTwo`. These two parameters are also the local variables of the `sum` function.

Note: if a function has inputs, the type of those inputs should be declared in the function prototype, but the names of variables are optional. In this case, when we defined the body of that function, we will set the name of those parameters as well.

Example: declaring a function in C

double maxNumber(int , double, float, long);

In the example above, the function’s name is `maxNumber`, the output’s type of this function is `double` and it has 4 parameters with the types of `int`, `double`, `float`, and `long`, respectively.

Note that these parameters don’t have a name for now, but we will set their name when we defined the function.

When defining a function, setting the names for parameters is necessary because these parameters are actually the local variables of the function and any variable should have a name!

As the last note: the order of parameters is important. When calling a function, we can’t just put a value randomly in a function or put less or more inputs than what actually is needed for that function! These actions will cause the compiler to return an error instead of compiling our source code.

For example, the prototype mentioned above needs 4 inputs (also called `arguments`) and the order is `int`, `double`, `float`, `long` respectively. So the correct way of calling this function would be:

maxNumber(1 , 3.2, 2.4f, 2235);

These are some examples of the wrong way of calling this function:

maxNumber(1 , 3.2);// less arguments than is expected.
maxNumber(1); // less arguments than is expected.
maxNumber(1 , 3.2, 2.4f, 2235,23,233); // inserting more arguments than what it can take.

All of these function calls will cause the compiler to return an error.

Again, don’t worry about how to call a function at this stage, as you’ll learn about how to call them later in this section.

2- How to define a Function in C:

Now that the function is declared, we need to define the logic within the body of that function.

These are the structures we can use to define a function:

Data_type function_name(){
// logic of the function goes here between open and close brackets.
return value; // the return keyword is only used when the function expected output.

}

Data_type function_name(data_type parameter_1, double parameter_2, double parameter_N ){
// logic of the function goes here between open and close brackets.
return value; // the return keyword is only used when the function expected output.

}

Data_type: the data-type of a defined function should be the same as its prototype. For example, if the prototype is `double` then the defined function should also set the return data type to `double`.

Function_name: the name of a defined function should be the same as its prototype. For example, if the prototype’s name is set to `sum` then the defined function should also be named as `sum`.

Parameters: the `type`, `number` and `order` of the parameters of a defined function should be the same as its prototype. But the `variable-name` for each parameter in the defined function can be different from what is set in the prototype of that function.

Open and close brackets {}: The logic of a function is defined within its body and the body of a function starts from the open brace `{` and ends right at the close brace `}`.

Note: there’s no need to put `;` after the close bracket.

return: if the defined function returns an output, we use the keyword `return` in order to set the value that the defined function should return. (The `return` keyword creates a statement and this statement must end with the semicolon `;`). (In the C Function return statement section, we’ve explained this statement in greater details.)

Note: if the defined function does not output any value (the output type is set to `void`) then there’s no need to use the `return` keyword.

Example: Defining a function in C

#include <stdio.h>

int sum(int v1 , int v2);

int main() {

    int result= sum(1,2);
    
    printf("result is: %d\n", result);
    return 0;
}

int sum(int valueOne , int valueTwo ){
    
    return valueOne + valueTwo; 
}

Output:

result is: 3

In the example above, we first declared a function named `sum` right above the `main` function. The return type of this function is `int`, the name as mentioned is `sum` and it takes two parameters both of type `int`.

After that, right below the body of the `main` function, the `sum` function is defined. As you can see, the return type + the name and the number of parameters of this function is exactly the same as its prototype. But parameters’ names are intentionally different, which is OK.

Also, because this function outputs a value of type `int`, within the body of the function, the keyword `return` is used, which in this case it returns the sum of two values (valueOne and valueTwo).

Note: it’s a compiler error if we try to define a function within the body of another function.

Example: C Void Function/ void keyword

Let’s run another example and this time the function won’t return any output, so the type is `void`:

#include <stdio.h>

void sum(int v1 , int v2);

int main() {

    sum(1,2);

    return 0;
}

void sum(int valueOne , int valueTwo ){
    int result = valueOne + valueTwo;
    printf("Result is: %d\n", (result));
}

Output:

Result is: 3

In this example because the `sum` function doesn’t return any output, we used `void` as the return type of this function which means `empty` and of course there’s no `return` keyword in the body of this function then.

Calling a Function in C: How to Call a Function in C?

In order to call a function, write the name of that function followed by a pair of parentheses () and end it with a semicolon `; `.

Structure:

Function_name();

If the called function takes arguments (inputs) then we need to put the inputs within the parentheses as well. This means we’re assigning values to the parameters of the function. The parameters, as mentioned before, are also the local variables of that function.

Structure:

Function_name( value1, value2, valueN);

Note: each input is separated via comma `, `.

You should know that calling a function can only happen within the body of another function or the body of itself, which in this case is called `recursion` and you can learn about it in the C recursion section.

Note: calling a function outside any function will cause a compile time error.

Example: calling a function in C

#include <stdio.h>

int multiply(int valueOne , int valueTwo);

int main() {

    int result = multiply(300,21);
    printf("Result is: %d\n", result);

    return 0;
}

int multiply(int valueOne , int valueTwo ){

    int result = valueOne * valueTwo;
    return result;
}

In the example above, we’ve called the `multiply` function within the body of the `main` function and because this function returns an `int` value, we’ve created a variable of this type in the body of `main` function and assigned the returned value of the `multiply` function to this variable.

Then in the next line we simply passed the value of the variable to another function called `printf` and so if you run the example, the result will be printed on the screen because of calling this `printf` function.

This last example might raise the question about how the instructions in a program run and where the entry point in a program is! You’ll get the answer to these questions and some others in later sections where we dive deep into the concept of `stack`.

What is argument in C?

The value we put as the input for a function when it’s being called is known as the arguments of that function.

Example: arguments in C

#include <stdio.h>

void printAge(int);
int main() {

    printAge(1000);
    return 0;
}
void printAge(int age){
    printf("%s%d\n", "My name is John Doe and my age is: ",age);
}

Output:

My name is John Doe and my age is: 1000

Here the `printAge()` function takes one argument and that should be of type int. So the value we’ve passed to this function in the `main` function is 1000 and this value is considered as the argument of the `printAge()` function. Note that this argument will be assigned to the `age` parameter and we can use this parameter in the body of the printAge() function to access the value then.

Return Type of a Function in C

If the data-type of a function is not `void` then that function returns a value of a specific data-type.

For example, the data type of a function could be `int`, `double`, `float`, `short`, a pointer, etc.!

The point is, the moment a function designed to return a value, in that function we should use the `return` statement in order to return a value.

A return statement is a combination of the `return` keyword and a value that we put on the right side of this operator.

For example:

return 10;

This statement sits inside the body of a function and it means when the execution engine reached to this statement in that function, it should terminate the work of the function and return the value 10 as a result.

Note: the data type of the value we put for the `return` statement should match the return data type of the enclosing function. For example, if the return data type of a function is set to double, then we need to return a double value!

Example: Functions with different return types in C

#include <stdio.h>

double multiply(double, double);
int sum(int, int);
int main() {

    double res = multiply(2.36, 56.4);
    int s = sum(14,15);
    printf("The value of the res variable is: %f\n",res);
    printf("The value of the sum variable is: %d\n",s);
    return 0;
}
double multiply(double val1, double val2){
    return val1 * val2; 
}
int sum(int val1, int val2){
    return val1+ val2;
}

Output:

The value of the res variable is: 133.104000

The value of the sum variable is: 29

Multiple return statements in a Function

In a function, there can be multiple return statements as well.

These statements mostly used when there are conditional statements like `if-else` or loops like `while` and `for` in a function and we want to terminate the work of a function in those statements if needed.

Example: using multiple return statements in a function

#include <stdio.h>

int sum(int, int);

int main() {

    int res = sum(100, 200);
    printf("The result is: %d\n",res);
    return 0;
}

int sum(int val1, int val2){
    int res = val2 + val1; 
    if (res>100){
        return 150; 
    }else{
        return 23;
    }
}

Output:

The result is: 150

C Local variables

A variable that is created within the body of a function is known as the local variable of that function.

A local variable, as the name suggest is local to its enclosing function! That means we can’t use such variable in other functions!

Note: the body of a function starts from the opening brace `{` and ends right at its closing brace `}`.

For example, let’s say a function named A and it has a local variable named `age`. Now if there’s another function (Let’s say the name of this second function is B), this function can’t access the `age` variable that belongs to the function A! Basically, to the eyes of the B function, there’s no such variable as `age` at all. So calling a variable named `age` in the body of the `B` function would result a compile time error.

Example: creating local variables in C

#include <stdio.h>

void printName(void);
int main() {

    printName();
    return 0;
}
void printName(void){
    int age =2000; 
    printf("%s%d\n", "My name is John Doe and my age is: ",age);
}

Output:

My name is John Doe and my age is: 2000

Here, in the body of the `printName()` function, there’s a variable named `age`. This is a local variable! That means we can’t access the age variable in the body of other functions like the `main`. If we do so, that would be a compile time error.

Types of Function in C

In short, there are two types of functions in C.

standard library functions in C:

These are the built-in functions that creators of C added to this language and we can use them whenever needed. For example, printf() function is a built in function in C where we can use to send data to the output.

User defined functions in C:

These are the functions that we as developers build in order to cover the tasks we want to be done in our programs.

Difference between Parameter and Argument

A parameter is the variable that we declare for a function and they are the local variables of the target function. Also, when we call a function, the input values we put for that function will be stored in these parameters.

On the other hand, arguments are those input values we put for a function when the function is being called.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies