Functions

Function is a code block that executes certain task.

Syntax

Void Example

A void function doesn't return any value.

Example:

Output:

Notice that printHi is defined before the main function which calls it.

Returning Result

Via the return keyword a result can be returned.

Let's have an example in which rectangle's area is calculated by passing arguments about it's sides.

Example:

Output:

There are couple of things to mark:

  • A functions is defined at lines 5 - 8. It accepts two arguments - widthArg and heightArg both of type double.
  • The function calcRectangleArea returns a double result.
  • calcRectangleArea is called at line 12.
  • It's returned value is set in the variable area.

Common Exceptions

Return Mismatch

If a function returns value different than the specified type, it causes an exception.

In this case 5 should be replaced with string value.

Arguments Type Mismatch

Atline 5 the function expects argument of type int.

At line 12 an argument of string type is passed.

The passed argument at line 12 should be replaced with integer value.

Arguments Count Mismatch

The function calcTrapezoidArea expects 3 arguments but only 2 are passed to it.

Calling function before it's definition

In C++ a function must be defined before it's call. Let's look at the following code:

In this case the functionprintHi should be moved above the main function.

Function Prototype

Function Prototype allows function to be called before it's definition..

Let's look at the following example:

Output:

At line 5 a function prototype is defined. For this reason we can call the printHi function though the function is defined (lines 12 - 15) after it's call (line 9).

Default Value

Default value may be specified for function parameters.

Let's look at the following:

Output:

At line 13 the function argument is not passed thus it takes the default value - 3 specified at line 5.