Lecture Five - Functions and Procedures
#include
<iostream>
using namespace std;
int main () {
int threeExpFour = 1;
for (int i = 0; i < 4; i = i + 1)
{
threeExpFour = threeExpFour * 3;
}
cout << "3^4 is " << threeExpFour << endl;
int sixExpFive = 1;
for (int i = 0; i < 5; i = i + 1)
{
sixExpFive = sixExpFive * 6;
}
cout << "6^5 is " << sixExpFive << endl;
int twelveExpTen = 1;
for (int i = 0; i < 10; i = i + 1)
{
twelveExpTen = twelveExpTen * 12;
}
cout << "12^10 is " << twelveExpTen << endl;
return 0;
}
With a function?
int main () {
int threeExpFour = raiseToPower (3, 4);
cout << "3^4 is " << threeExpFour << endl;
int sixExpFive = raiseToPower(6, 5);
cout << "6^5 is " << sixExpFive << endl;
int twelveExpTen = raiseToPower(12, 10);
cout << "12^10 is " << twelveExpTen << endl;
return 0;
}
In general, we use (call) functions (aka: modules, methods, procedures, subprocedures, or subprograms) to perform a specific (atomic) task.
if f(x) = 2x + 5, then f(1) = 7, f(2) = 9, and f(3) = 11
1, 2, and 3 are arguments
7, 9, and 11 are the corresponding values
The caller invokes (calls) a function by using its name and argument list in an expression.
Functions are building blocks
Examples of standard c++ functions: pow(x,y), sqrt(x), floor(x)
Function header is defined by returning type, name, and parameters.
returnName functionName(dataType variableName, dataType variableName) //function header
Function body is defined by list of statements between {} and return statement. Function returns as soon as a return statement is executed.
{
functionBody
return value;
}
In C/C++ up to one value may be returned; it must be the same type as the return type.
Function call results in execution of body of called function. Important! Function declarations need to occur before invocations.
//function call syntax:
x = functionName(actual parameter list);
Call to value-returning function with empty formal parameter list (assigning returned value is optional):
x = functionName();
Call to void function with empty formal parameter list:
functionName();
//Value-returning function definition syntax: including header and body
functionType functionName(formal parameter list) //function header
{
//function body
statements...
//value-returning function return statement
return expression;
}
Formal parameter list can be empty: parentheses still required.
Example :
//value-returning function call (assignment):
y = 2.0 * sqrt(x);
Void functions are created and used just like value-returning functions except they do not return a value after the function executes.
In some language such a function will be called procedure.
//Void (NonValue-returning) function definition syntax: including header and body
void functionName(formal parameter list) //function header
{
//function body
statements...
//void (nonvalue-returning) function can still use return statement
//but, does not return any values...
return;
}
//function call syntax:
functionName(actual parameter list); //stand-alone statement only
Notice that return statement here is optional.
Example:
//void function call:
cin.get();
Another example:
//void function call with parameter:
printName(name);
Value Parameter: formal parameter receives copy of content of corresponding actual parameter
Reference Parameter: formal parameter receives location (memory address) of corresponding actual parameter
void functionName(dataType variable, dataType variable) //function header
{
}
void functionName(dataType& variable, dataType& variable) //function header
{
}
The return statement only allows you to return 1 value.
Passing output variables by reference overcomes this limitation.
void swap(int &a, int &b) {
int t = a;
a = b;
b = t;
}
int main() {
int q = 3;
int r = 5;
swap(q, r);
}
What is going to happen? Notice that we pass variables by value which is a pointer.
#include
using namespace std;
void square (int *x, int *y)
{
*x = (*x) * --(*y);
}
int main ( )
{
int number = 30;
square(&number, &number);
cout << number;
return 0;
}
Output :
Problem:
void funcA()
{
funcB();
....
}
void funcB()
{
....
}
As it stands, this would not compile. When the compiler encounters the call to to funcB(), it doesn't yet know that funcB() exists.
Function prototype: function heading without body of function.
Function prototypes appear before function definitions--that is, before function main().
Copy function header and add a semi-colon (;)--however, you don't need parameter names, only data types
//function prototype syntax: only data types (not names) of parameters must be specified
functionType functionName(formal parameter list);
Example:
//function prototypes
double testTwo(double, double);
double testThree(double x, double y, double z);
It is not obligatory to use prototypes!
int add(int,int);
int main()
{
std::cout << add(3,1) << std::endl;
}
int add(int x, int y)
{
return x + y;
}
When return statement executes in function main(), program terminates.
If the execution of main() ends normally without encountering a return statement the compiler assumes the function ends with an implicit return statement:
return 0;
0 means that function main() finished its execution successfully,
Any other value stands for the code of error.
When we have more than one functions with the same name.
Used when different data types will be used with the same function.
When overloading a function, dissimilar signatures must be used for each overloaded version. A function signature consists of a list of data types of its parameters, as well as their order, and number.
Example:
//valid overloaded function prototypes (applicable to definitions as well)...
void myFunc();
void myFunc(int i);
void myFunc(char c);
void myFunc(char c, int i);
void myFunc(int i, char c);
void myFunc(string & s);
//Error: differs from void myFunc(); only by return type
int myFunc();
//OK: Different signature
int myFunc(float f);
The value of a default parameter is specified when the function name appears for the first time (as in the prototype).
When a function is called, the number of actual and formal parameters must be the same except in the case of default parameters.
All default parameters must be the rightmost parameters of function.
Example:
//function prototype...applies to definitions as well...
void myFunc(int x, int y, double t, char z = 'A', int u = 50,
char v='B', double w = 18.56);
//local variables
int a, b;
char ch;
double d;
//legal function calls
myFunc(a, b, d);
myFunc(a, 15, 36.1, 'C', 92, ch);
myFunc(b, a, 13.21, 'D');
//illegal function calls
myFunc(a, 15, 33.1, 62.3);
myFunc(b, 25, 32.9, 'E', 1234, 92.7);
What will happen here?
#include<iostream>
using namespace std;
int fun(int x = 0, int y = 0, int z)
{ return (x + y + z); }
int main()
{
cout << fun(10);
return 0;
}
Output:
What will happen here?
#include <iostream>
using namespace std;
int Add(int X, int Y, int Z)
{
return X + Y;
}
double Add(double X, double Y, double Z)
{
return X + Y;
}
int main()
{
cout << Add(5, 6);
cout << Add(5.5, 6.6);
return 0;
}
Output:
a.c: In function ‘int main()’:
a.c:25:29: error: no matching function for call to ‘Add(int, int)’
cout << Add(5, 6);
A function that calls itself is called recursive.
Recursive function must terminate! - knows how to solve the simplest case(s).
Example:
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
else
return 1;
}
What is the return value of f(p, p) if the value of p is initialized to 5 before the call? Note that the first parameter is passed by reference, whereas the second parameter is passed by value.
int f(int &x, int c) {
c = c - 1;
if (c == 0) return 1;
x = x + 1;
return f(x, c) * x;
}
Output:
For very short functions, it may be more efficient to simply insert the code of the function where it is called, instead of performing the process of formally calling a function.
Keyword inline suggest the compiler that the code generated by the function body shall be inserted at each point the function is called, instead of being invoked with a regular function call.
inline string concatenate (const string& a, const string& b)
{
return a+b;
}
This informs the compiler that when concatenate is called, the program prefers the function to be expanded inline, instead of performing a regular call (many compilers use this trick even if we do not specify a function as inline).
The functions are declared in header files which are included by the preprocessor directive
#include <filename.h>
The directive #include "filename.h" searches only the current directory for header files.
For large programs it can be useful to write new header files.
Header files should contain only function declarations, variable declarations and preprocessor directives.
Header files only declare functions. The actual object code is often located in libraries, consisting of (pre-compiled) object files.
Libraries are generally distributed as the header file containing the prototypes, and a binary .dll/.so file containing the (compiled) implementation.
Library user only needs to know the function prototypes (in the header file), not the implementation source code (in the .cpp file)
The Linker (part of the compiler) takes care of locating the implementation of functions in the .dll file at compile time.
In C, like normal data pointers (int , char, etc), we can have pointers to functions.
Declaration of function:
int foo(int);
Let put * operator between int and foo(int)
int * foo(int);
Warning! Operator () will take priority over operator *.
And the above declaration will mean – a function foo with one argument of int type and return value of int * i.e. integer pointer.
Finally
int (*foo)(int);
In C, like normal data pointers (int , char, etc), we can have pointers to functions.
void fun(int a)
{
printf("Value of a is %d\n", a);
}
int main()
{
// fun_ptr is a pointer to function fun()
void (*fun_ptr)(int) = &fun;
/* The above line is equivalent of following two
void (*fun_ptr)(int);
fun_ptr = &fun;
*/
// Invoking fun() using fun_ptr
(*fun_ptr)(10);
return 0;
}
// Two simple functions
void fun1() { printf("Fun1\n"); }
void fun2() { printf("Fun2\n"); }
// A function that receives a simple function
// as parameter and calls the function
void wrapper(void (*fun)())
{
fun();
}
int main()
{
wrapper(fun1);
wrapper(fun2);
return 0;
}
Such a code :
#include<iostream>
using namespace std;
int &fun()
{
int x = 10;
return x;
}
int main()
{
cout << fun();
return 0;
}
def test():
print('in test function')
test()
Warning! Function blocks must be indented as other control-flow blocks.
Functions in Python can optionally return values. By default, functions return None.
You call the functions as in C
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
As in C/C++ functions take parameters.
def double_it(x):
return x * 2
We can also define default value and make parameter optional.
def double_it(x=2):
return x * 2
double_it()
4
double_it(3)
6
Keyword arguments are related to the function calls.
When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
#!/usr/bin/python
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )
Functions is Python can return more than one value!
# This function returns a tuple
def fun():
str = "geeksforgeeks"
x = 20
return str, x; # Return tuple, we could also
# write (str, x)
# Driver code to test above method
str, x = fun() # Assign returned tuple
print(str)
print(x)
http://www.cs.fsu.edu/~cop3014p/lectures/ch7/index.html
http://www.cs.fsu.edu/~cop3014p/lectures/ch6/index.html
https://www.tcd.ie/Engineering/courses/BAI/JF_Subjects/1E3/lectures/8Abstraction.pdf
http://www.dcs.bbk.ac.uk/~roger/cpp/week5.htm
http://www.cplusplus.com/doc/tutorial/functions/
http://www.nada.kth.se/kurser/master/intro/Course04-05/Handouts/Flecture05.pdf
http://www.scipy-lectures.org/language/functions.html
http://www.geeksforgeeks.org/function-pointer-in-c/
https://en.wikibooks.org/wiki/Python_Programming/Functions
http://www.geeksforgeeks.org/how-to-declare-a-pointer-to-a-function/