Declaring functions

Location
  1. Courses

    /

  2. Complete C++ Course

    /

  3. The basics

    /

  4. Declaring functions

Why declaring functions?

A function can not be called somewhere in the code before it has been defined (or declared). Look at this code:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream> int main() { func(5); // Error: The function 'func' does not exist here. Return 0; } void func(int arg) { std::cout << arg << std::endl; }

Inside the main function, the compiler is not aware that the function func exists as it is defined later. We could resolve that by placing the definition of func before the definition of the function main:

1
2
3
4
5
6
7
8
9
10
void func(int arg) { std::cout << arg << std::endl; } int main() { func(5); // It works. Return 0; }

Now, let us consider an other example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void func1(int a) { if(a > 0) { a--; func2(a); // Error: The function 'func2' does not exist here. } } void func2(int a) { if(a > 0) { a-=2; func1(a); } }

Both functions call each other. Here, we can not resolve the problem by putting the function definition of func2 before func1 because if we do so, then it will be the function func1 that will not exist inside func2. To resolve that, we use what is called function declarations. It is basically used to tell the compiler that there is a function named x that takes x parameters and returns a value of type x that is defined later (Or in an other file). The compiler is then aware of the existence of that function and no error is caused. However, if the function is never defined, the linker will fail and send an error message.

Declaring functions

We declare a function by writing its header (The same as the function definition, but without the braces) followed by a semicolon ;.

By declaring the functions before defining them, the example above now works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void func1(int a); void func2(int a); void func1(int a) { if(a > 0) { a--; func2(a); // It now works. } } void func2(int a) { if(a > 0) { a-=2; func1(a); } }

In function declarations, the name of the arguments are optional. We could declare the functions above like that:

void func1(int); void func2(int);

Here is the example from the beginning, resolved by declaring the function func:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream> void func(int arg); int main() { func(5); // It now works. Return 0; } void func(int arg) { std::cout << arg << std::endl; }

Note that, unlike in the function definitions, in the declarations, writing the name of the arguments is optional:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream> void func(int, float); int main() { func(5, 2.5); Return 0; } void func(int arg, float arg2) { std::cout << arg * arg2 << std::endl; }