Foundations of programming

Lecture Five - Functions and Procedures

WorkPlan

  1. Introduction, types of programming languages, pseudocode
  2. Variables, data types
  3. Pointers and arrays
  4. Simple instructions and tricks
  5. Functions and Procedures
  6. Input / Output
  7. Error Types /Debug
  8. Data Structures
  9. Modern C++
  10. Python
  11. Python II
  12. Python III
  13. Object Oriented / Functional programming
  14. Software development in XXI century
  15. Final exam / Test

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

Copy-Paste

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

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 fstream header.
Function prototypes for C-style string-processing are in cstring 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 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.

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 (assigning returned value is optional):

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

Test

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 :

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

It is not obligatory to use prototypes!

Example:

int add(int,int);

int main()
{
    std::cout << add(3,1) << std::endl;
}

int add(int x, int y)
{
    return x + y;
}

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

Test

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:

Test

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:

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

Crazy example

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:

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

Function pointers

Such a code :

#include<iostream> 
using namespace std; 

int &fun() 
{ 
    int x = 10; 
    return x; 
} 
int main() 
{ 
    cout << fun(); 
    return 0; 
} 
  1. May cause runtime error
  2. May cause compiler error
  3. Always works fine.
  4. Return 0

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

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

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/

https://www.geeksforgeeks.org/c-references-question-1/