# Lesson 9.5. Arrays and functions

## Passing arrays as arguments

As for variables, it is possible to pass an array as an argument to a function. The syntax consists in adding empty square brackets in the arguments of the function to specify that it is an array and not a variable:

``````void init(int tab[], int size) {
int i=0;
for (i=0; i<size; i++) tab[i]=0;
}``````

However, passing arrays as parameters to functions has some differences with variables. The function does not receive a copy of the array (as for variables). It receives the address of the first cell of the array. This has two major consequences:

• When an array is passed as a parameter to a function, its content can be modified by the function code. In the example above, we can see that the function returns nothing (`void init()`). It will directly modify the content of the array passed to it as a parameter.

• The size of the array is not known to the function. It is therefore necessary to inform the function about the size of the array. In the example above, a second parameter `size` is passed to the function. `size` informs the function about the number of cells in the array.

## Keyword const

The keyword `const` placed before an argument tells the compiler and the user of the of the function that this argument will not be modified by the function. For example, the following function displays an array without modifying its content:

``void display(const int tab[]);``

Specifying that an array cannot be modified by a function is a good programming habit. This allows some compilers to perform additional checks at compile time.

## Exercises

In the following exercises, we will consider the declaration of the constant `NB_GRADES` and and the following 3 arrays:

``#define NB_GRADES 6``
``````float grades1[NB_GRADES] = {10.2, 12.5, 18.5, 9.8, 13.2, 12.1};

### Exercise 1

Write a function `void display(const float grades[], int size)` which displays the values of the array passed as parameter. Test your function with the array `grades1` :

```grade    = 10.20
```

### Exercise 2

Write a function `int init(float class[], int size, float value)` that fills the array `class` with the note `grade`. Initialize each cell of `grades2` array to 10 thanks to the function before displaying it:

```grade    = 10.00
```

## Quiz

In C, an array passed as an argument to a function ...

The `tab` array passed as argument ...

``void fct(int tab[]);``

The `tab` array passed as argument ...

``void fct(const int tab[]);``

How can a function know the size of an array?

The keyword `const` ...