You are on page 1of 7

Functions in C++ What is user defined function: A function is a group of statements that together perform a task.

Every C++ program has at least one function which is main(), and all the programs can also define additional functions. Good C++ programmers write programs that consist of many of these small functions. Program written with numerous functions is easier to maintain, update and debug than one very long program. By programming in a modular (functional) fashion, several programmers can work independently on separate functions which can be assembled at a later date to create the entire project. Each function has its own name. When that name is encountered in a program, the execution of the program transferred to the body of that function. When the function is finished, execution returns to the area of the program code from which it was called, and the program continues on to the next line of code. Types of functions There are 2(two) types of functions as: 1. Built in Functions 2. User Defined Functions
1. Built in Functions (library functions):
These functions are also called as 'library functions'. These functions are provided by system. These functions are stored in library files. e.g. clrscr(), sqrt(), getch(), strlen(), strcat() etc.

2. User Defined Functions :


The functions which are created by user for program are known as 'User defined functions'.

Creating User-Defined Functions 1. Declare the function. The declaration, called thefunction prototype, tells the computer the name, return type, and parameters of the function. This statement is placed after #include<iostream.h> (and other headers) and before int main(void).

2.Define the function. 1

The function definition tells the compiler what task the function will be performing. A function definition cannot be called unless the function is declared. The function prototype and the function definition must agree EXACTLY on the return type, the name, and the parameters. The only difference between the function prototype and the function header is a semicolon (see diagram below). The function definition is placed OUTSIDE the main()function.
The general form of a C++ function definition is as follows:

return_type function_name( parameter list ) { body of the function }

A C++ function definition consists of a function header and a function body. Here are all the parts of a function: Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature. Parameters(arguments): A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Function Body: The function body contains a collection of statements that define what the function does.

EXAMPLE: #include<iostream.h> #include<conio.h> int max(int num1, int num2);// Function Declaration(prototype) int main() { // local variable declaration: int a = 100; int b = 200; int ret; // calling a function to get max value. ret = max(a, b); //Function call with two parameters a & b cout << "Max value is : " << ret; getch(); return 0; } // function returning the max between two numbers int max(int num1, int num2) // Function Definition { int result; // local variable declaration if (num1 > num2) result = num1; else result = num2; return result; //Function returning a value } ===========================================

Describe the following prototypes


Style 1: void functionName(void)

Our first style of function will simply perform an independent task. It will not send or receive any parameters and it will notreturn any values. The word void appears as the return typeand the parameters.
Style 2: void functionName(argument(s))

Our second style of function will take arguments (parameters) but will not return a value. The argument list in the parentheses specifies the types and number of arguments that are passed to the function. void sum(int x, int y, int z); //function prototype Using variable names in the prototype does not actually create the variables. It merely states the "type" of variables that will be used. Within the program, the function call sends actual values to the function to be processed by the function. sum(75, 95, 83); //function call
Style 3: non-void functionName(void)

Our third style of function takes no arguments, but will return a value. Up until now, we have been communicating information TO a called function. Now we will be returning information FROM the function by using the function return value. The return valuecan be a constant, a variable, or an expression. The only requirement is that the return value be of the type specified in the function prototype. return_type functionName(void) //function header { statements; return (value); //value is of type return_type } Function calls that return values need to have a place in main for the returned value to reside, to be printed, or to be manipulated. Think of the function as holding out its hand to pass a value back to main. Main must stretch out its hand (which may be a variable location) for this value to reside. Always be sure to do something with a returned value! Store the return value somewhere; print the return value to the screen; use the return value in a calculation; just use it!! The following are examples of USES of function return values: (Function calls with return locations) x = Avg( i, j) (Function Avg takes i and j and returns a value stored in x.) cout<< num(1,3,5); (Function num takes 1, 3 and 5 and its return value is printed) ans=add(a,b) + add(c,d); (Function add is called twice. The return values from 2 calls are added and stored in ans.)
Style 4: non-void functionName(arguments)

Our fourth style of function takes arguments AND returns a value. ===========================================

Actual arguments & Formal arguments OR Explain calling function and called function Actual arguments: The arguments that are passed in a function call are called actual arguments. These arguments are defined in the calling function. Formal arguments: The formal arguments are the parameters/arguments in a function declaration. The scope of formal arguments is local to the function definition in which they are used. Formal arguments belong to the called function. Formal arguments are a copy of the actual arguments. A change in formal arguments would not be reflected in the actual arguments. Example: #include <iostream.h> void sum(int i, int j, int k); int main() { int a = 5; sum(3, 2 * a, a); // actual arguments *calling function* return 0; } //called function void sum(int i, int j, int k) //formal arguments { int s; s = i + j + k; cout<<sum is:<<s; } ===========================================

Pass by value and pass by reference in functions Normally Parameters to a functions are passed in two ways either pass by value or pass by reference.
Pass by Value:

In this method, the value of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function. In pass by value, the changes made to formal arguments in the called function have no effect on the values of actual arguments in the calling function. Example: #include <iostream.h> #include<conio.h> void swap(int x, int y) { int t; t = x; x = y; y = t; } int main() { int m = 10, n = 20; clrscr(); cout<<Before executing swap m= <<m<< n=<<n<<endl; swap(m, n); //call by value cout<<After executing swap m= <<m<< n=<<n; getch(); return 0; } Output: Before executing swap m=10 n=20 After executing swap m=10 n=20 Explanation: In the main function, values of variables m, n are not changed though they are passed to function 'swap'. Swap function has a copy of m, n and hence it cannot manipulate the actual value of arguments passed to it. 6

Pass by Reference:

In this method, the addresses of actual arguments in the calling function are copied into formal arguments of the called function. This means that using these addresses, we would have an access to the actual arguments and hence we would be able to manipulate them.
Example:

#include <iostream.h> #include<conio.h> void swap(int x, int y) // function definition { int t; t = x; /* assign the value at address x to t */ x = y; /* put the value at y into x */ y = t; /* put the value at to y */ } int main() { int m = 10, n = 20; clrscr(); cout<<Before executing swap m= <<m<< n=<<n<<endl; swap(&m, &n); //pass by reference cout<<After executing swap m= <<m<< n=<<n; getch(); return 0; } Output: Before executing swap m=10 n=20 After executing swap m=20 n=10
Explanation:

In the main function, address of variables m, n are sent as arguments to the function 'swap'. As swap function has the access to address of the arguments, manipulation of passed arguments inside swap function would be directly reflected in the values of m, n What is the purpose of main() function
In C++, program execution starts from the main() function. Every C++ program must contain a main() function. The main function may contain any number of statements. These statements are executed sequentially in the order which they are written. The main function can in-turn call other functions. When main calls a function, it passes the execution control to that function. The function returns control to main when a return statement is executed or when end of function is reached. In C++, the function prototype of the 'main' is one of the following: int main(void); //main with no arguments

You might also like