C++ Functions

Functions are reusable code blocks that will only execute when called. It is a section of a program that can act on data and return a value. This function can contain statements that call other functions, some of which might call others, and so on.

Advantages

A well-designed function performs a specific task. Complicated tasks should be broken down into multiple functions, which each can be called in turn. This makes your code easier to understand and maintain. It provides modularity and code reusability.

Types of Functions

There are two types of functions in C programming:

Library Functions are the the inbuilt C++ functions which are declared in the C++ header files such as ceil(x), cos(x), exp(x), etc.

User-defined functions: are the functions which are created by the programmer which is reusable. It reduces complexity of a big program and optimizes the code.

CPP Functions 1

Declaration of a function

Syntax

The syntax of creating C++ function is given below:

return_type function_name(data_type parameter_list...)
{  
//code to be executed  
}

The return_type specifies the type of data that the function returns. A function may return any type of data except an array. The parameter_list is a comma-separated list of variable names and their associated types that receive the values of the arguments when the function is called.

function_name(type varname1, type varname2, . . . , type varnameN)

For example, here are correct and incorrect function parameter declarations:

f(int i, int k, int j) /* correct */
f(int i, k, float j) /* incorrect */

A function may be without parameters, in which case the parameter list is empty.

Example #1
snippet
void myFunction()
{
cout << "Hello World";
}
Example #2

Let's see the simple example of C++ function.

snippet
#include <iostream>
using namespace std;
void func() {  
   static int i=0; //static variable  
   int j=0; //local variable  
   i++;  
   j++;  
   cout<<"i=" << i<<" and j=" <<j<<endl;  
}  
int main()
{
 func();  
 func();  
 func();  
}
Output
i= 1 and j= 1 i= 2 and j= 1 i= 3 and j= 1

Calling Functions

The function above will simply print out a text message when it is called. To invoke it from the main function the function's name is specified followed by a set of parentheses.

Example
snippet
void myFunction()
{
cout << "Hello World";
}

int main()
{
myFunction(); // "Hello World"
}

Function Arguments/ Parameters

The parentheses that follow the function name are used to pass arguments to the function in the form of comma separated list. To use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.

Example
snippet
void myFunction(string a, string b)
{
cout << a + " " + b;
}

A function can be defined to take any number of parameters, and they can have any data types. Just ensure the function is called with the same types and number of arguments.

snippet
myFunction("Hello", "World"); // "Hello World"

Default Function Parameters

We can specify default values for parameters by assigning them a value inside the parameter list.

Example #1
snippet
void myFunction(string a, string b = "Earth")
{
cout << a + " " + b;
}

If that argument is unspecified when the function is called the default value will be used instead. When a function has more than one parameter, default values are assigned based on the order of the parameters.

snippet
myFunction("Hello"); // "Hello Earth"
Example #2

If a parameter does not have a default value, parameter may have a default value.

Here’s a prototype with four parameters:

snippet
long set4DPoint(int x, int y, int z, int t); //Valid

long set4DPoint(int x, int y, int z = 1, int t); //Invalid

Returning from Function

Functions return a value or void, a data type that represents a nonvalue in C++.

To return a value from a function, the keyword return is followed by the value to return. The value can be a literal, a variable, or an expression, because all expressions produce a value.

Here are some examples

Example #1
snippet
return 5;
return (x > 5);
return (convert(fahrenheit));
Example #2
snippet
int getSum(int a, int b)
{
return a + b;
}

The return is a jump statement that causes the function to exit and return the specified value to the place where the function was called.

Example #3
snippet
cout << getSum(5, 10); // 15
Example #4

The return statement can also be used in void functions to exit before the end block is reached.

snippet
void dummy() { return; }
Note
Though the main function is set to return an integer type, it does not have to explicitly return a value. This is because the compiler will automatically add a return zero statement to the end of the main function.
int main() { return 0; }

Inline Functions

When using functions, every time a function is called, a performance overhead occurs. To remove this overhead you can recommend that the compiler inlines the calls to a specific function by using the inline function modifier. This keyword is best suited for small functions that are called inside loops.

snippet
inline int myInc(int i) { return i++; }
Note
The inline keyword should not be used on larger functions since inlining these can severely increase the size of the code, which will instead decrease performance. The inline keyword is only a recommendation. The compiler may in its attempts to optimize the code choose to ignore this recommendation and it may also inline functions that do not have the inline modifier
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +