Functions in C++

A function is a block of statements which is used to perform a task. Any C++ program has at least one function which is main().  When you have a piece of code that is often repeated you should put it into a function and call that function instead of repeating the code.

Function Definition

You define a function in similar way as you define the main function. First put return type then the function name and function parameters in brackets. The function code goes between curly brackets.

returnType functionName( parameters ) {

statement(s);

}

Example

void PrintHello()
{

cout << “Hello\n”;

}

Calling a Function

Once you have created the function you can call it from the main program. Here is an example of how to call the PrintHello function.

void PrintHello()
{

cout << “Hello\n”;

}

void main()
{

PrintHello();

}

Local and Global Variables

If you declare a variable inside a function it is only accessible by that function and is called a local variable. If you declare a variable outside of all functions it is accessible by any function and is called a global variable.

Example

int g; // Global variable

void MyFunction()
{

int l; // Local variable
l = 5;
g = 7;

}

void main()
{

g = 3;

}

Function Arguments

The arguments are used to pass values to a function. Arguments goes between the brackets after the function name. You must choose the datatype of all parameters. Here is a function that receives a number as a parameter and then prints it.

void PrintNumber(int n, int m)
{

cout << n << m;

}

void main()
{

PrintNumber(5, 6);

}

Passing Parameters by Reference

You can either pass a parameter by reference or by value. The default is by value which means that a copy of the variable is made for that function. If you use a * in front of the parameter then you will be passing only a pointer to that variable instead of making another copy of it.

void PrintNumber(int *n)
{

cout << *n;

}

void main()
{

int i = 5;
PrintNumber(&i);

}

Returning Values

A function can return a value that you can store in a variable. We have been using void in the place of the return variable until now. Here is an example of how to return the number 5 from a function and store it in a variable.

int GetNumber()
{

return 5;

}

void main()
{

int i = GetNumber();

}

Leave a Reply

Your email address will not be published. Required fields are marked *