# Lesson 8.4. Return keyword

## Introduction

`return` is a C keyword that has a double purpose:

• it ends the execution of the function;
• it returns a value or a variable to the entity that called the function (the main program or another function).

In a function of type `void fct()`, the return is optional. If it is present, it is necessarily written as `return;` without value.

A function can only return one value. We will see later on other mechanisms (pointers or structures) that allow a function to return several values.

## Syntax

Note that `return` is a C keyword that must be common to all ANSI compliant compilers. Since `return` is not a function, parentheses are not necessary:

``return (5);``

should rather be written :

``return 5;``

The `return` keyword can be followed by

• a value ;
• a calculation;
• a symbolic constant
• a variable;
• a call to a function.

Here are some examples:

``````// Value
return 35.65;

// Calculation
return 2*3.1415;

// Constante
return M_PI;

// Variable
return maVariable;

// Function
return cos(3.1415);``````

## Exercise

Write a function `int isPrime(unsigned int n);` which receives a positive integer `n` as parameter.

• If `n` = `0` : the function returns `0`.
• If `n` = `1` : the function returns `0`.
• If `n` is divisible by an integer in the interval [2;n[, the function returns this integer.
• If `n` is a prime number, the function returns `1`.

A prime number is a natural number that has exactly two distinct positive integer divisors (1 and itself).

Test the function with the following code in the main program:

``````unsigned int x, p;

// Ask for a positive integer
printf("Enter a positive integer: ");
scanf ("%u", &x);

// Check if the integer entered is a prime number
p = isPrime (x);
switch (p) {
case 0: printf ("By convention, 0 and 1 are not prime numbers.\n"); break;
case 1: printf ("%u is prime.\n",x); break;
default: printf ("%u is a divisor of %d.\n", p, x); break;
}``````

Here are some examples of expected outputs:

```Enter a positive integer: 1
By convention, 0 and 1 are not prime numbers.
```
```Enter a positive integer: 125
5 is a divisor of 125.
```
```Enter a positive integer: 11
11 is prime.```

## Quiz

In C, the `return` keyword is used to :

Let's consider the following function:

``void fct(int i);``

`return` is...

What the following function displays:

``````void test() {
printf ("Hello");
return;
print f("Bye");
}``````

Which syntaxes allow to return several values?