Foundations of programming

Lecture five - Functions and Procedures

Work Plan

  1. Introduction, types of programming languages, pseudo-code
  2. Variables, data types
  3. Pointers and arrays
  4. Simple instructions and tricks
  5. Functions and procedures
  6. Data structures
  7. Input / Output
  8. Debug
  9. Operators, Iterators
  10. Polymorphism
  11. Functional / object oriented programming
  12. Advanced topics, threads
  13. Software development process, agile, tdd
  14. Final Test during last classes: about 30 open/close questions - mostly closed.

Functions

image

Copy-Paste

#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; 
} 

Functions

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.

image

The role of functions

image

Why to use functions?

Functions are building blocks

Function syntax

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.

Predefined functions

Examples of standard c++ functions: pow(x,y), sqrt(x), floor(x)

Predefined functions are organized into separate libraries:
I/O functions are in iostream header. Math functions are in cmath header. Function prototypes for conversions of numbers to text, text to numbers, memory allocation, random numbers and various other utility functions are in cstdlib header. Function prototypes for the C-style standard input/output library are in cstdio header. Function prototypes for functions that perform input from files on disk and output to files on disk are in cstring header. Function prototypes for C-style string-processing are in fstream header.

Examples 1

image

Examples 2

image

User-defined functions

Two types:
void functions: no return type, do not return a value value-returning functions: have a data type, return only one value to caller
Header (or heading) includes:
function name number of parameters (if any) data type of each parameter type of function (data type or void)
Body includes:
code to accomplish task variables (if any) declared in body of function are local to function

Function call

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:

x = functionName(); 

Call to void function with empty formal parameter list:

functionName(); 

Value returning function

//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 function

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-Returning and Void functions: similarities

Value-Returning and Void functions: differences

Good practices:

Functions parameters

Value Parameter: formal parameter receives copy of content of corresponding actual parameter

Reference Parameter: formal parameter receives location (memory address) of corresponding actual parameter

image

Value parameter

Value Parameter:
* Value of corresponding actual parameter copied into formal parameter * Value parameter has own copy of data * During program execution, value parameter manipulates data stored in own memory space * Value parameters will accept expressions, constants, or variables from actual parameters (i.e., in function call)
void functionName(dataType variable, dataType variable) //function header
{

}

Reference Parameters

Reference Parameter:
* Formal parameter receives and stores address of corresponding actual parameter * During program execution, address stored in reference parameter can modify data of corresponding actual parameter, by sharing same memory space * Reference parameters can: pass one or more values from function, and can change value of actual parameter * Reference parameters useful in three situations: a) Returning more than one value, b) Changing value of actual parameter c) When passing address would save memory space and time * Reference parameter limitations: reference parameters will not accept expressions or constants from actual parameters (i.e., in function call), ONLY variables
void functionName(dataType& variable, dataType& variable) //function header
{

}

Example

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);  
}     

Value or reference?

image

Value or reference?

Pass by value:
Makes copy of actual parameter Passes copy of contents Original variable's contents DO NOT change Implementation: default behaviour Safer
Pass by reference:
Passes address of actual parameter Accesses original variable's contents (via address) Original variable's contents DO change Implementation: Add ampersand (&) before parameter name in header and prototype More efficient

Example:

//prototype functions
void readDate(int& month, int& day, int& year); //reference parameters
void printDate(int month, int day, int year); //value parameters

int main()
{
    //initialize automatic variables
    int mm, dd, yy;
    readDate(mm, dd, yy);
    printDate(mm, dd, yy);

    return 0;
}

//function definitions
void readDate(int& month, int& day, int& year)
{
    char ch; //local variable
    cout << "Enter a date (mm/dd/year): ";
    cin >> month >> ch >> day >> ch >> year;
}

void printDate(int month, int day, int year)
{
    cout << "The date is " << month << '-' << day;
    cout << '-' << year << endl;
}    

Function prototype

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 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 x, double y);
double testThree(double x, double y, double z);

It is not obligatory to use prototypes!

Flow of execution

Function call invocation:
* Transfer of control to first statement in body of called function * After function body executed: control passed back to point immediately following function call * Value-returning function returns value * After function execution: value that function returns replaces function call statement

Function main()

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.

Function Overloading

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);

Default parameters

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);

Recursion

A function that calls itself is called recursive.

Recursive function must terminate! - knows how to solve the simplest case(s).

Drawbacks for Recursion:
* Can be expensive in both processor time and memory space * Each call creates another set of the functions variables

Example:

long factorial (long a)
{
    if (a > 1)
        return (a * factorial (a-1));
    else
        return 1;
}

Inline functions

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).

Header files

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.

Libraries

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.

Function Pointers

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);

Function pointers

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;
}

Properties

// 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;
}

Crazy

image

Functions in Python

Defining functions:
* the def keyword; * is followed by the function’s name, then * the arguments of the function are given between brackets followed by a colon :. * the function body ; * and return object for optionally returning values.
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.

Example

image

Calling the function

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")

Parameters

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

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" )

Value or reference?

Parameters to functions are reference to objects, which are passed by value.

When you pass a variable to a function, python passes the reference to the object to which the variable refers (the value), not the variable itself.

If the value is immutable, the function does not modify the caller’s variable. If the value is mutable, the function may modify the caller’s variable in-place:

def try_to_modify(x, y, z):
    x = 23
    y.append(42)
    z = [99] # new reference
    print(x)
    print(y)
    print(z)

a = 77    # immutable variable
b = [99]  # mutable variable
c = [28]
try_to_modify(a, b, c)
>> 23
>> [99, 42]
>> [99]
print(a)
>> 77
print(b)
>> [99, 42]
print(c)
>> [28]

Return parameters

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)

image

Variable-Length Argument Lists

Python allows you to declare two special arguments which allow you to create arbitrary-length argument lists.

This means that each time you call the function, you can specify any number of arguments above a certain number.

def function(first,second,*remaining):
    statement1
    statement2

When calling the above function, you must provide value for each of the first two arguments.

However, since the third parameter is marked with an asterisk, any actual parameters after the first two will be packed into a tuple and bound to "remaining."

def print_tail(first,*tail):
    print tail

print_tail(1, 5, 2, "omega")
print_tail(5, 2, 'omega')

References

http://www.cs.fsu.edu/~cop3014p/lectures/ch7/index.html

http://www.cs.fsu.edu/~cop3014p/lectures/ch6/index.html

https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-096-introduction-to-c-january-iap-2011/lecture-notes/MIT6_096IAP11_lec03.pdf

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/