C++ chapter 2
C++ chapter 2
Chapter 2
Function in C++
Compiled by: Desiyalew Haregu
@CCI, WKU, 2014 EC.
Syntax:
Return-type Function-name (parameters) function header
{ statement 1;
statement 2;
:
: Function body
:
statement N;
Compiled By: Desiyalew H. @2014 14
}
Declaring, defining and calling function
Defining function
Example:
Example :
// same name different arguments
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }
Here, all 4 functions are overloaded functions.
Notice that the return types of all these 4 functions are not the same.
Compiled By: Desiyalew H. @2014 30
Function Overloading
Overloaded functions may or may not if (var < 0.0)
have different return types but they var = -var;
must have different arguments. For return var;
example, }
// Error code // function with int type parameter
int test(int a) { } int absolute(int var) {
double test(int b){ }
if (var < 0)
Here, both functions have the same var = -var;
name, the same type, and the same return var;
number of arguments. Hence, the }
compiler will throw an error. int main() {
// Program to compute absolute value // call function with int type parameter
// Works for both int and float/Overloading Using Different cout << "Absolute value of -5 = " <<absolute(-5) << endl;
Types of Parameter // call function with float type parameter
#include <iostream> cout << "Absolute value of 5.5 = " << absolute(5.5f) <<
using namespace std; endl;
// function with float type parameter return 0;
Compiled By: Desiyalew
} H. @2014 31
float absolute(float var){
Default Arguments in C++ Functions
The default arguments are used cout<<sum(1)<<endl;
when you provide no arguments or /* In this case a value is passed as
only few arguments while calling a * 1 and b value as 2, value of c values is
* taken from default arguments.
function. */
declarations are valid /* Since a has default value assigned, all the
int sum(int a=10, int b=20, int c=30); * arguments after a (in this case b and c) must
int sum(int a, int b=20, int c=30); have
int sum(int a, int b, int c=30); * default values assigned, b has default value but
* c doesn't have, thats why this is also invalid
Invalid: Following function declarations */
are invalid int sum(int a=10, int b=20, int c);
/* Since a has default value assigned, all the
* arguments after a (in this case b and c) must
have
* default values assigned
*/
int sum(int a=10, int b, int c=30);
/* Since b has default value assigned, all the
* arguments after b (in this case c) must have
* default values assigned
*/ Compiled By: Desiyalew H. @2014 33
Recursive Functions
Recursive function can be defined as a routine that calls itself directly
or indirectly.
The process may repeat several times, outputting the result and the end
of each iteration.
Syntax:
recursionfunction()
{
recursionfunction(); //calling self function
}