You are on page 1of 39

Functions

1 CUIT111 SEST, CUT 10/30/2020


Outline
 Understanding a function
 Functions and Local Variables
 Functions and Global Variables
 Invoking a function
 Parameter passing
 Examples
 Function Prototypes
 Recommendations

2 CUIT111 SEST, CUT 10/30/2020


Understanding a functions
 A function is a group of statements that achieve a complete task.
 Have a purpose
 Can be used repeatedly with different parameters etc.
 Can be invoked externally
 Make maintenance much easier and timely
 Make debugging easier
 Examples
 Calls to printf(“hello”)
 A function printf that is fully defined in stdio.h
 main()
 A special purpose function that indicates the where program execution starts
and ends
 There are mainly three forms of functions

3 CUIT111 SEST, CUT 10/30/2020


Understanding functions – type 1
 Receives nothing
 Does not send anything out
 Simply does action

action

4 CUIT111 SEST, CUT 10/30/2020


Understanding functions – type 2
receive something  Receive something =
parameters
 Does an action(s)
 Does not send anything out
action

5 CUIT111 SEST, CUT 10/30/2020


Understanding functions – type 3
 Receives nothing
 Send something out =
return value/result

action

send something out

6 CUIT111 SEST, CUT 10/30/2020


Understanding functions – type 4
receive something  Receive something =
parameters
 Send something out =
return value/result
action  parameter

send something out

7 CUIT111 SEST, CUT 10/30/2020


Structure of a function

return_type function_name ( list of parameters)


{
//local variable declaration

//statements

//return statement if return_type not void


}

 Return_type is the data type of the data thrown out by the function
 Data is thrown out in the return statement
 Return statement data type must match that of return_type
 void is used if function returns no value

8 CUIT111 SEST, CUT 10/30/2020


Scoping our function variables
 Currently we will consider functions that make use of
global variables
 Those recognised throughout a C program
 Those defined soon after the #include and #define statements
but before the main() function

9 CUIT111 SEST, CUT 10/30/2020


Why different parameters for some
functions?
 The different values we pass to printf() suggest there is
high flexibility in the definition of printf()

 printf(“hey”);
 Means the function can handle
 char* cs
 printf(“value is %d”, num);
 Means the function can also handle
 char*cs + list_of_names);

10 CUIT111 SEST, CUT 10/30/2020


Writing functions (1)
 Write a program that accepts two numbers from the user,
adds the two numbers and outputs the results

 accepts two numbers two integer variables


 from the user, two printf/scanf statements
 adds the two numbers a variable for the total and
a statement using +
 outputs the results a printf statement

11 CUIT111 SEST, CUT 10/30/2020


Writing functions (2)
 Write a program that accepts two numbers from the user, adds the two numbers
and outputs the results

#include <stdio.h>
int a, b;
int c;
main()
{
printf(“Enter first whole number:”);
scanf(“%d”, &a);
printf(“Enter first whole number:”);
scanf(“%d”, &b);
c = a + b;
printf(“Total of two numbers is: = %d”, c);
}

12 CUIT111 SEST, CUT 10/30/2020


Revisiting functions – type 1
 Receives nothing
 Does not send anything out
 Simply does action

action

13 CUIT111 SEST, CUT 10/30/2020


Writing functions (3)
 Write a function called input() that accepts user input for two numbers,
assuming the variables for the two numbers are defined as global to the
program

void input()
{ printf(“Enter first whole number:”);
scanf(“%d”, &a);
printf(“Enter second whole number:”);
scanf(“%d”, &b);
}
 void means the function is not throwing out a value
 () means the parameter list is empty
 The above is an example of a general purpose function.

14 CUIT111 SEST, CUT 10/30/2020


Writing functions
Assume that a, b, and c are already defined as global
variables as follows:
#include <stdio.h>
int a, b, c;

 Write a function called add() that adds a and b and stores


the result in c.
 Write a function called display() that prints out the value
in c.
 Write a function called multiply() that multiplies a, b and
c and then overwrites c, then prints out the value in c.
15 CUIT111 SEST, CUT 10/30/2020
All type 1 functions
#include <stdio.h> void display()
int a, b, c;
{
void input()
{ printf(“Enter first whole number:”); printf(“value in c = %d”, c);
scanf(“%d”, &a); }
printf(“Enter first whole number:”);
scanf(“%d”, &b);
void multiply()
}
{
void add() c = a * b * c;
{ printf(“new value of c =
c = a + b; %d”, c);
}
}
16 CUIT111 SEST, CUT 10/30/2020
Invoking a type 1 function
 Invoking a function
 Is calling a function to make use of it, just like we do printf OR
 Is making use of a function
 Type 1 functions are simply called by name.
 They receive nothing
 They send out nothing

17 CUIT111 SEST, CUT 10/30/2020


Invoking type 1 functions
#include <stdio.h> void display()
{
int a, b, c;
printf(“value in c = %d”, c);
}
void input()
{ printf(“Enter first whole number:”); void multiply()
{
scanf(“%d”, &a); c = a * b * c;
printf(“Enter first whole number:”); printf(“new value of c = %d”, c);
scanf(“%d”, &b); }

}
main()
{
void add() input();
{ add();
//invoke display, and multiply
c = a + b; // what happens if you switch add() and input()?
} }

18 CUIT111 SEST, CUT 10/30/2020


Revisiting functions – type 2
receive something  Receive something =
parameters
 Does an action(s)
 Does not send anything out
action

19 CUIT111 SEST, CUT 10/30/2020


Writing type 2 functions (1)
 List the parameters separated by commas
 Give each parameter a name of your choice
 Single letters are better
 These parameters are only known to the function
 Then do whatever is required with the parameter value
void addxy(int x, int y) { }

void raise(int y, double x) { }

void raise (double x, int y ) { }

void addxy(int a) { }

20 CUIT111 SEST, CUT 10/30/2020


Writing type 2 functions (2)
 Write a function called mult() that accepts an integer,
multiplies it by two, stores the result in a variable y and
prints out the value of y.

void mult(int x)
{
y = x * 2;
printf(“value of y = ”, y);
}

21 CUIT111 SEST, CUT 10/30/2020


Invoking a type 2 function
 Since a type 2 function has parameters only
 Does not send something out
 It is used by name and a value
 This is called Function call by value
 If changes not required to the value/variable that is passed
 To call mult, one can do the following:
int num;
main()
{
num = 8;
mult(num);
mult(3 * 16);
mult(num/3);
mult(27384);
}

22 CUIT111 SEST, CUT 10/30/2020


Revisiting functions – type 3
 Receives nothing
 Send something out =
return value/result

action

send something out

23 CUIT111 SEST, CUT 10/30/2020


Writing type 3 functions (1)
 This particular function sends out a value (only one)
 The keyword return is used to indicate the value sent
 E.g. 1. return 5; sends out the value 5
 E.g.2. return num; sends out the variable num (including its value)
 E.g.3. return num/2; sends out the result of calculating num/2

 This function must indicate the type of value it is sending out.


 This is done in the function declaration part
 Therefore void is no longer used
 E.g.1. int show() {..... } means that the function is to have a return
statement that returns an integer value or integer variable.
 E.g.2. float show() { .....} means the function must have a return
statement that returns a float value or float variable.

24 CUIT111 SEST, CUT 10/30/2020


Writing type 3 functions (2)
 Putting it together:
 Suppose we want a function called multxy that sends out the
result of calculating two integers x and y. The result is stored in
the value b.
 The function would be defined as:

int multxy()
{
b = x * y;
return b;
}

25 CUIT111 SEST, CUT 10/30/2020


Invoking type 3 functions
 These functions #include <stdio.h>
int x, y, result;
 Receive nothing int multxy()
 Send something out {
b = x * y;
 Whatever is sent out must return b;
be received so that it does }
not get lost. main()
{
 Continuing with our
printf(“enter x and y: );
example: scanf(“%d %d”, &x, &y);
result = multxy();
printf(“Result is %d”, result);
printf(“Result is %d”, multxy());
}

26 CUIT111 SEST, CUT 10/30/2020


Revisiting functions – type 4
receive something  Receive something =
parameters
 Send something out =
return value/result
action  parameter

send something out

27 CUIT111 SEST, CUT 10/30/2020


Writing type 4 functions (1)
 These
 Receive something
 Send something out
 Bring together type 2 and type 3
 Defining type 4 functions
 list the parameters in the brackets
 State the return type
 Have a return statement
 Invoking type 4 functions
 Have a value in which to receive result
 In the brackets, pass a value or variable

28 CUIT111 SEST, CUT 10/30/2020


Writing type 4 functions (2)
 Write a function called greatest() that receives two float
parameters, finds the greatest value of the two, and
returns the greatest number of the two values. If the values
are the same, the function should return 0;

float greatest(float a, float b)


{
if (a > b) return a;
else if (b > a) return b;
else return
}

29 CUIT111 SEST, CUT 10/30/2020


Invoking type 4 functions
 Two things main()
 Pass a value {
 Receive the result printf(“enter x and y: ”);
scanf(“%f %f”, &x, &y);
#include <stdio.h>
float x, y, res; res = greatest(x,y);
float greatest(float a, float b) if (res == 0.0)
{ printf(“values are
if (a > b) return a; equal”);
else if (b > a) return b; else
else return 0.0; printf(“greatest = %f”, res);
}

30 CUIT111 SEST, CUT 10/30/2020


Now back to global and local issues
 Functions and programs recognise variables within their
area of influence
 A function body in { } can have variables that it defines
within the { }
 These are known only within the { }
 These are called local variables
 Local variables are usually for convenience
 You want to see if your calculations are correct
 You want to break down a complex formula in sub-parts
 You want to temporarily store some values
 Let’s explore the following examples on the effects of
global and local variables in programming.
31 CUIT111 SEST, CUT 10/30/2020
Example 1: local versus global variables

Program code Run Results


#include <stdio.h>
Initial total value = 5
void printName()
{ Harriet
int total = 2; printf("\n Harriet"); total += 3;
printf("\n\n total plus 3 = %d", total);
} total plus 3 = 5
int main()
{ total times 3 = 15
int total = 5;
printf("\n\n Initial total value = %d", total); Process returned 21 (0x15)
printName(); total *= 3; execution time : 0.016 s
printf("\n\n total times 3 = %d", total);
} Press any key to continue.
32 CUIT111 SEST, CUT 10/30/2020
Example 2: global variables

Program Code Run Results


#include <stdio.h>
int total = 2;
Initial total value = 2
void printName() Harriet
{
printf("\n Harriet"); total += 3;
printf("\n\n total plus 3 = %d", total); total plus 3 = 5
}

int main()
total times 3 = 15
{
printf("\n\n Initial total value = %d", total); Process returned 21 (0x15)
printName(); total *= 3; execution time : -0.000 s
printf("\n\n total times 3 = %d", total);
} Press any key to continue.
33 CUIT111 SEST, CUT 10/30/2020
Example 3: Function call by value

Program Code Run Results


#include <stdio.h>
int total = 0;
Initial total value = 0
void printName(int num) Harriet
{
printf("\n Harriet"); total = num + 3;
printf("\n\n %d plus 3 = %d", num, total); 4 plus 3 = 7
}

int main() total times 3 = 21


{
printf("\n\n Initial total value = %d", total); Process returned 21 (0x15)
printName(4); //flexible start values execution time : 0.000 s
total *= 3; printf("\n\n total times 3 = %d", total);
} Press any key to continue.
34 CUIT111 SEST, CUT 10/30/2020
Example 4: handling return values

Program Code Run Results


#include <stdio.h> Initial total value = 0
int total = 0;
int printName(int num) Harriet
{
printf("\n Harriet"); total = num + 3;
printf("\n\n %d plus 3 = %d", num, total);
4 plus 3 = 7
return total;
}
total times 3 = 21
int main() Process returned 21
{ (0x15) execution time
printf("\n\n Initial total value = %d", total); : 0.010 s
total = (printName(4))* 3; //handling return value
printf("\n\n total times 3 = %d", total); Press any key to
} continue.
35 CUIT111 SEST, CUT 10/30/2020
Example 5: Function call by reference

Program Code Run results


#include <stdio.h> Initial total value = 4
int printName(int *addr)
{ Harriet
printf("\n Harriet"); *addr = *addr + 3;
printf("\n\n value plus 3 = %d", *addr);
return *addr; value plus 3 = 7
}

int main() total times 3 = 21


{ Process returned 21
int total = 4;
(0x15) execution time :
printf("\n\n Initial total value = %d", total);
total = (printName(&total))* 3;
0.016 s
printf("\n\n total times 3 = %d", total); Press any key to continue.
}

36 CUIT111 SEST, CUT 10/30/2020


Operator overloading
 Not possible in C but in C++

37 CUIT111 SEST, CUT 10/30/2020


Function Prototypes
 Are function declarations without any body.
 Simply state the expected structure of the full definition of the function
 What we have been seeing in previous slides are function definitions
 Examples of function declarations

int printName(int *addr);

void print_name(int num);


 Are usually declared after the preprocessor directives or before the
function definitions
 A function declaration does not make it mandatory that the function be
immediately defined.
 Definitions can be done later.

38 CUIT111 SEST, CUT 10/30/2020


Recommendations
 Things to avoid
 Unnecessary variables
 Duplication of variables and functionalities
 Over-clustering
 Over-modularising

39 CUIT111 SEST, CUT 10/30/2020

You might also like