chapter 6: functions – modular programming
DESCRIPTION
CHAPTER 6: Functions – Modular Programming. CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon. Topics. Categories of functions Built-in or predefined or standard functions Programmer-defined functions Working with programmer-defined functions - PowerPoint PPT PresentationTRANSCRIPT
CHAPTER 6: Functions – Modular Programming
CSEB113 PRINCIPLES of PROGRAMMING CSEB134
PROGRAMMING I
byBadariah Solemon
1BS (May 2012)
Topics1. Categories of functions
– Built-in or predefined or standard functions– Programmer-defined functions
2. Working with programmer-defined functions– Declaring functions prototypes– Calling Functions– Defining Functions
3. Types of programmer-defined functions– Receive no input parameter and return nothing,– Receive no input parameter but return a value,– Receive input parameter( one or more) and return nothing– Receive input parameter( one or more) and return a value
4. More about functions– Multiple return Statements in a Function– Working with Multiple Functions– Effect of Local and Global Variables– Effect of Auto and Static Storage Classes
2BS (May 2012)
CATEGORIES OF FUNCTIONS
Topic 1
BS (May 2012) 3
Introduction• Most computer programs that solve real-world problems are
much larger than the programs presented in the first few chapters.
• Experience has shown that the best way to develop and maintain a large program is to construct it from smaller pieces or modules.
• Modules in C are called functions.– A function is a block of code which is used to perform a specific task.– A function is reusable and therefore prevents programmers from
having to unnecessarily rewrite what they have written before
• C programs are typically written by combining new functions you write with built-in functions available in the C Standard Library.
BS (May 2012) 4
A Program with Functions and Structure Chart
• Suppose that you were assigned to write a program that displays the house as shown in Fig 1.
• Drawing the house can be broken into two tasks:– Task 1: draw the roof– Task 2: draw the ground floor
• This is best illustrated and explained in the form of a structure chart as shown in Fig 2.
BS (May 2012) 5
Draw a house
Draw the roof Draw the ground floor
^ . .. .------------------| || || ----- || | | || | | |------------------
Fig 1
Fig 2
A Program with Functions and Structure Chart
• Based on the identified tasks, the program can be written with two new functions as below. The chart (previous page) now becomes the chart with actual function names.
BS (May 2012) 6
#include <stdio.h>void roof(void);void floor(void);
void main(void){ roof(); floor();}
void roof(void){ printf(“ ^ \n” “ . . \n” “. .\n”);}
#include <stdio.h>void roof(void);void floor(void);
void main(void){ roof(); floor();}
void roof(void){ printf(“ ^ \n” “ . . \n” “. .\n”);}
void floor(void){ printf(“------------------\n” “| |\n” “| |\n” “| ----- |\n” “| | | |\n” “| | | |\n” “------------------\n”);}
void floor(void){ printf(“------------------\n” “| |\n” “| |\n” “| ----- |\n” “| | | |\n” “| | | |\n” “------------------\n”);}
main
floorroof
Categories of Functions
BS (May 2012) 7
Functions
Pre-defined Functions
Programmer-defined Functions
Input / Output
Functions:printf()scanf()getchar()putchar()
Input / Output
Functions:printf()scanf()getchar()putchar()
OthersOthersFunctions without
input parameter and do not return any
value
Functions without
input parameter and do not return any
value
Functions without
input parameter and return
a value
Functions without
input parameter and return
a value
Functions with input
parameters (one or
more) and do not
return any value
Functions with input
parameters (one or
more) and do not
return any value
Functions with input parameter
(one or more) and
return a value
Functions with input parameter
(one or more) and
return a value
Built-in functions provided by C
Built-in functions provided by C
Functions that are written by the programmers
themselves to carry out various individual tasks.
Functions that are written by the programmers
themselves to carry out various individual tasks.
What are Pre-defined Functions?
• Pre-defined at the standard C libraries. – Example: printf(), scanf(), pow(), ceil(), rand(), etc.
• What we need to do to use them is to include the appropriate header files.– Example: #include <stdio.h>,#include <math.h>
• What contained in the header files are the prototypes of the standard functions. The function definitions (the body of the functions) has been compiled and put into a standard C library which will be linked by the compiler during compilation.
BS (May 2012) 8
Header Files
BS (May 2012) 9
<assert.h> Contains macros and information for adding diagnostics that aid program debugging.
<ctype.h> Contains function prototypes for functions that test characters for certain properties, convert lowercase letters to uppercase and vice versa.
<errno.h> Defines macros that are useful for reporting error condition.
<float.h> Contains the floating point size limits of the system.
<limits.h> Contains the integral size limits of the system.
<math.h> Contains function prototypes for math library functions.
<setjump.h> Contains function prototypes for function that allow bypassing of the usual function call and return sequence.
More Header Files
BS (May 2012) 10
<signal.h> Contains function prototypes and macros to handle various conditions that may arise during program execution.
<stdarg.h> Defines macros for dealing with a list of arguments to a function whose number and types are unknown.
<stddef.h> Contains common definitions of types used by C for performing certain calculations.
<stdio.h> Contains function prototypes for the standard input/output library functions and information used by them.
<stdlib.h> Contains function prototypes for conversions of numbers to text and text to numbers, memory allocation, random numbers, and other utility functions
<string.h> Contains function prototypes for string processing functions.
<time.h> Contains functions prototypes and types for manipulating time and date.
WORKING WITH PROGRAMMER-DEFINED FUNCTIONS
Topic 2
BS (May 2012) 11
What Should I do?• In order to write and use your own function,
you need to:1. Declare Function Prototype(s)
• Also called function declaration/prototype.
2. Call Function • Call the function whenever it needs to be used.
3. Define Function • Also known as function definition/implementation,
which define the function somewhere in the program (usually after the main function).
BS (May 2012) 12
• To declare a function prototype, identify:– A type of returned value – either void or same as type of a value
returned to the caller.– A function name.– An optional list of parameter enclosed in ().
• Use commas to separate more than one parameter types. Use (void) or () if there is no parameter.
– A terminating semicolon.
• The format:
• Example:void roof(void); int GetScore();void CalculateTotal(int);char Testing(char, char);
How Do I Declare a Function Prototype?
BS (May 2012) 13
type-of-returned-value function-name (parameter-list);type-of-returned-value function-name (parameter-list);
How Do I Call a Function?• A function is called by the declared function name (prototype).• To call a function, make sure you know :
– The function name.– An optional list of parameters, enclosed in () – use blank() if there is no
parameter.– A terminating semicolon– Type of a value returned from the called function (if any)
• Two formats to call a function:
• Example:roof(); printMenu(3);printMenu(3, answer);printMenu(x+y, sum);val = printMenu(x);
BS (May 2012) 14
1) function-name (parameter–list);2) variable-to hold-returned-value = function-name (parameter-list);1) function-name (parameter–list);2) variable-to hold-returned-value = function-name (parameter-list);
How Do I Define a Function?• A function definition is where the actual code for the function
is written. This code will determine what the function will do when it is called.
• To define a function, identify:– The type of returned value - either void or same as type of a value
returned to the caller.– The function name.– An optional list of formal parameters enclosed in parentheses
(function arguments)– A compound statement ( function body) – use braces { }
• The format:
BS (May 2012) 15
type-of-returned-returned-value function-name (parameter-list){ declaration-statement; executable-statement;}
type-of-returned-returned-value function-name (parameter-list){ declaration-statement; executable-statement;}
Function definition header – must be the same as function prototype
TYPES OF PROGRAMMER-DEFINED FUNCTIONS
Topic 3
BS (May 2012) 16
Types• The four types (refer earlier slide) of programmer-defined
functions discussed in this chapter are categorized based on a value returned and input parameters from each function.
• Can be determined from the function prototypes.
BS (May 2012) 17
Type Returned Value
Input Parameter
Function Prototype - Examples
1 No No void functionX (void);
2 Yes No int functionX (void);char functionY (void);float functionZ (void);
3 No Yes(One or More)
void functionX (int a);void functionY (float p, int r);
4 Yes Yes(One or More)
int functionX (int a);float functionY (float p, int r);char functionZ (char c, char d);
FUNCTIONS WITHOUT INPUT PARAMETER AND DO NOT RETURN ANY VALUE
Topic 3-1
BS (May 2012) 18
Example
• Observe that both the function prototype and the function definition header are very similar
BS (May 2012) 19
#include <stdio.h>
void printMenu(void);
void main(void)
{
printMenu();
}
void printMenu(void)
{
printf(“This program draws a rectangle\n”);
}
#include <stdio.h>
void printMenu(void);
void main(void)
{
printMenu();
}
void printMenu(void)
{
printf(“This program draws a rectangle\n”);
}
Calling a function
Defining a function – usually after the end of main () function
function type – void means the function does not return any value
list of parameter type – void means NO input parameter
Declaring a function prototype
Leaving the bracket() blank means the function being called does not receive any parameter
Conceptual View & Flowchart
BS (May 2012) 20
void main(void)
{
printMenu();
}
void printMenu(void)
{
printf(“This
program draws
a rectangle\n”);
}
Source code *.c
Print“This program
draws a rectangle”
Print“This program
draws a rectangle”
BeginBegin
EndEnd
BeginBegin
EndEnd
printMenu()
void main(void) void main(void) void printMenu(void) void printMenu(void)
This program draws a rectangle
main
printMenu
Data flow from or to another function – blank flow line means no input or returned value
More Example
BS (May 2012) 21
#include <stdio.h>
void printRect(void);
void main(void)
{
printRect();
printRect();
printRect(); //A function can be called repeatedly
}
void printRect(void)
{
printf (“------------------------\n”
“| |\n”
“------------------------”);
}
#include <stdio.h>
void printRect(void);
void main(void)
{
printRect();
printRect();
printRect(); //A function can be called repeatedly
}
void printRect(void)
{
printf (“------------------------\n”
“| |\n”
“------------------------”);
}
------------------------| |------------------------------------------------| |------------------------------------------------| |------------------------
Exercise 1• Rewrite the following program by implementing a
programmer-defined function named myFC.• The program shall call the myFC function from the main
function. The reading and printing tasks must be completed in the myFC function.
BS (May 2012) 22
#include<stdio.h>main (){
int num;
printf("Enter an integer [or -99 to exit]:");scanf("%d",&num);do{
printf("Number is: %d\n",num);printf("Enter an integer [or -99 to
exit]:");scanf("%d",&num);
} while (num != -99);}
#include<stdio.h>main (){
int num;
printf("Enter an integer [or -99 to exit]:");scanf("%d",&num);do{
printf("Number is: %d\n",num);printf("Enter an integer [or -99 to
exit]:");scanf("%d",&num);
} while (num != -99);}
Exercise 2• Write program that calls a programmer-defined
function named printMsg1. • Within the printMsg1 function, ask the users for
their annual income. Then, print a congratulatory message if the user makes more than RM100,000 a year or an encouragement message if the user makes less. A sample input/output of the program is as shown below:
BS (May 2012) 23
Enter annual income: RM120000.00
** Well done! **
FUNCTIONS WITHOUT INPUT PARAMETER AND RETURN A VALUE
Topic 3-2
BS (May 2012) 24
same data type
Example
BS (May 2012) 25
#include <stdio.h>int printMenu(void);
void main(void) { int y; y = printMenu(); printf(“The return value is: %d”, y);}
int printMenu(void) { int x=99; printf(“This program draws a rectangle\n”); return x;}
#include <stdio.h>int printMenu(void);
void main(void) { int y; y = printMenu(); printf(“The return value is: %d”, y);}
int printMenu(void) { int x=99; printf(“This program draws a rectangle\n”); return x;}
Declaring Function prototype(s)
Call function
Define function
Each function may return only one value but might have multiple return statements in its
Conceptual View & Flowchart
BS (May 2012) 26
void main(void)
{
int y;
y = printMenu();
printf(“The return value is: %d”, y);
}
int printMenu(void)
{
int x=99;
printf(“This program draws a rectangle\n”);
return (x);
}
Source code *.c
99
main
printMenu
99
Conceptual View & Flowchart
BS (May 2012) 27
Print “This program draws
a rectangle”
Print “This program draws
a rectangle”
BeginBegin
EndEnd
BeginBegin
EndEnd
y = printMenu()
void main(void) void main(void) int printMenu(void) int printMenu(void)
This program draws a rectangle The return value is 99
Printy
Printy
x = 99x = 99
Return xReturn x
main
printMenu
99
Returning a Value from a Function
• A return statement must appear anywhere in the body of the function definition.
• The form of the return statement is:
• Example:– return x; // assume the declaration int x=4;
– return x*3;– return 12;– return ‘B’;– return (10); //also acceptable
BS (May 2012) 28
return expression/value ;return expression/value ;
More Example
BS (May 2012) 29
#include <stdio.h>float findTotal(void);
void main(void) { float y; y = findTotal(); printf(“Total mark: %.2f\n”, y); printf(“Total: %.2f\n”, findTotal()-10.00);}
float printTotal(void) { float x=80.00, z=10.5, p; p = x + z; return p;}
#include <stdio.h>float findTotal(void);
void main(void) { float y; y = findTotal(); printf(“Total mark: %.2f\n”, y); printf(“Total: %.2f\n”, findTotal()-10.00);}
float printTotal(void) { float x=80.00, z=10.5, p; p = x + z; return p;}
Total mark: 90.50Total: 80.50
Exercise• Write program that calls a programmer-defined function
named printMsg2. Within the printMsg2 function, ask the users for their annual income.
• Then, return the amount of income to the main function.
• In the main function, print a congratulatory message if the user makes more than RM100,000 a year or an encouragement message if the user makes less.
BS (May 2012) 30
FUNCTIONS WITH INPUT PARAMETERS AND DO NOT RETURN ANY VALUE
Topic 3-3
BS (May 2012) 31
#include <stdio.h>
void printMenu(int x);
void main(void)
{
printMenu(3);
}
void printMenu(int x)
{
printf(“This program draws %d rectangles”, x);
}
#include <stdio.h>
void printMenu(int x);
void main(void)
{
printMenu(3);
}
void printMenu(int x)
{
printf(“This program draws %d rectangles”, x);
}
Example: Function with One Input Parameter
BS (May 2012) 32
Formal parameter
Actual parameter
3
This program draws 3 rectangles
main
printMenu
3
Methods to Call a Function with Input Parameters
The methods:1. Call by value
– In this method, copy of actual parameter’s value is passed to the function. Any modification to the passed value inside the function will not affect the actual value.
2. Call by reference– In this method, the reference (memory address) of the variable
is passed to the function. Any modification passed done to the variable inside the function will affect the actual value.
– To do this, we need to have knowledge about pointers and arrays (pointers are NOT be discussed in this subject and arrays are discussed in Chapter 7).
BS (May 2012) 33
Importance Points• Three important points concerning functions with
parameters are:1. The number of actual parameters in a function call
must be the same as the number of formal parameters in the function definition.
2. A one-to-one correspondence must occur among the actual and formal parameters. The first actual parameter must correspond to the first formal parameter and the second to the second formal parameter, an so on.
3. The type of each actual parameter must be the same as that of the corresponding formal parameter.
BS (May 2012) 34
Calling a Function by Value
BS (May 2012) 35
#include <stdio.h>
void printMenu(int x);
void main(void)
{
printMenu(3); //Function call
}
void printMenu(int x)
{
printf(“This program draws %d
rectangles”, x);
}
#include <stdio.h>
void printMenu(int x);
void main(void)
{
printMenu(3); //Function call
}
void printMenu(int x)
{
printf(“This program draws %d
rectangles”, x);
}
Various possible ways to call the printMenu() function include:1. Assign a constant value. E.g:
2. Assign a variable value. E.g:
3. Assign an expression value. E.g:
printMenu(3);
printMenu(y); //y must be of type int
printMenu(y*4%2); //end-value of arithmetic expression must be of type int
Note: The actual parameter of the function call must be of the same type with the formal parameter – in the function prototype or function definition header
Calling a Function with One Parameter: Example
BS (May 2012) 36
#include <stdio.h>void printMenu(int x);
void main(void) {
int y = 10; printMenu(y); printMenu(y*3);}
void printMenu(int x) {
printf(“This program draws %d rectangles”, x);}
#include <stdio.h>void printMenu(int x);
void main(void) {
int y = 10; printMenu(y); printMenu(y*3);}
void printMenu(int x) {
printf(“This program draws %d rectangles”, x);}
Formal parameter
Actual parameter
10
main
printMenu
10
Calling a Function with Two Parameters: Example
BS (May 2012) 37
#include <stdio.h>
void printMenu(int x, char ans);
main()
{
char answer = ‘y’;
printMenu(3, answer);
}
void printMenu(int x, char ans)
{
if (ans == ‘y’ || ans == ‘Y’)
printf(“This program draws %d rectangles”, x);
}
#include <stdio.h>
void printMenu(int x, char ans);
main()
{
char answer = ‘y’;
printMenu(3, answer);
}
void printMenu(int x, char ans)
{
if (ans == ‘y’ || ans == ‘Y’)
printf(“This program draws %d rectangles”, x);
}
main
printMenu
3
‘y’
More Example
BS (May 2012) 38
#include<stdio.h>void convertNumber(int x, int y);
void main(void) {
int first, second;printf("Please enter the first number: ");scanf("%d", &first);printf("Please enter the second number: ");scanf("%d", &second);
convertNumber(first, second);}
void convertNumber(int x, int y){
int temp=0;if(x > y)
printf("\n%d is bigger than %d. \n\n", x, y); else if (x < y) printf("\n%d is smaller than %d. \n\n", x, y); else
Printf(“\n%d is equals to %d.\n\n”, x, y);}
#include<stdio.h>void convertNumber(int x, int y);
void main(void) {
int first, second;printf("Please enter the first number: ");scanf("%d", &first);printf("Please enter the second number: ");scanf("%d", &second);
convertNumber(first, second);}
void convertNumber(int x, int y){
int temp=0;if(x > y)
printf("\n%d is bigger than %d. \n\n", x, y); else if (x < y) printf("\n%d is smaller than %d. \n\n", x, y); else
Printf(“\n%d is equals to %d.\n\n”, x, y);}
Please enter the first number:4Please enter the second number: 10
4 is smaller than 10
Exercise• Write program that calls a programmer-defined function
named printMsg3. • Ask the users for their annual income in the main function.• Then, pass the value of income from the main function to the printMsg3 function. In the printMsg3 print a congratulatory message if the user makes more than RM100,000 a year or an encouragement message if the user makes less.
BS (May 2012) 39
FUNCTIONS WITH INPUT PARAMETERS AND RETURN A VALUE
Topic 3-4
BS (May 2012) 40
#include <stdio.h>int printMenu(int x);
void main(void) { int y; y = printMenu(3); printf(“The return-value: %d\n”, y);}
int printMenu(int x) {
printf(“This program draws %d rectangles\n\n”, x);return x+2;
}
#include <stdio.h>int printMenu(int x);
void main(void) { int y; y = printMenu(3); printf(“The return-value: %d\n”, y);}
int printMenu(int x) {
printf(“This program draws %d rectangles\n\n”, x);return x+2;
}
Functions with One Input Parameter and Return a value: Example
BS (May 2012) 41
Declare Function prototype(s)
Define function
Call function
This program draws 3 rectangles
The return-value: 5
main
printMenu
35
Functions with Two Parameters and Return a Value: Example
BS (May 2012) 42
#include <stdio.h>
char printMenu(int x, char ans);
main()
{
char answer = ‘y’, r;
r = printMenu(3, answer);
printf(“Return character: %c”, r);
}
char printMenu(int x, char ans)
{
if (ans == ‘y’ || ans == ‘Y’)
printf(“This program draws %d rectangles”, x);
return ‘N’;
}
#include <stdio.h>
char printMenu(int x, char ans);
main()
{
char answer = ‘y’, r;
r = printMenu(3, answer);
printf(“Return character: %c”, r);
}
char printMenu(int x, char ans)
{
if (ans == ‘y’ || ans == ‘Y’)
printf(“This program draws %d rectangles”, x);
return ‘N’;
}
main
printMenu
3
‘y’‘N’
Exercise• Write a program that calls a programmer-defined function named
printMsg4. • Ask the users for their annual income in the main function.• Then, pass the value of income from the main function to the
printMsg4 function. • In the printMsg4 function, if the user makes more than RM100,000,
print a congratulatory message and assign character ‘A’ to variable grade. If the user makes less, print an encouragement message and assign character ‘Z’ to variable grade.
• Next, return the value of grade variable to the main function. In the main function, print the returned value on the screen. A sample input/output of the program is as shown below:
BS (May 2012) 43
Enter annual income: RM120000.00
** Well done! ** [A]
MORE ABOUT FUNCTIONS
Topic 4
BS (May 2012) 44
Sub-topics• Multiple return statements in a function• Working with multiple functions• Effect of local and global variables accessed by
functions in a program• Types and effects of auto and static storage
classes to local and global variables
BS (May 2012) 45
MULTIPLE return STATEMENTS IN A FUNCTION
Topic 4-1
BS (May 2012) 46
Example
BS (May 2012) 47
#include <stdio.h>int printMenu(void);
void main(void) { int y; y = printMenu(); printf(“The return value is: %d”, y);}
int printMenu(void) { int x=99; if (x > 90) { printf(“This program draws a rectangle\n”); return x; } else return x*2;}
#include <stdio.h>int printMenu(void);
void main(void) { int y; y = printMenu(); printf(“The return value is: %d”, y);}
int printMenu(void) { int x=99; if (x > 90) { printf(“This program draws a rectangle\n”); return x; } else return x*2;}
A return statement must appear anywhere in the body of the function
main
printMenu
99 or 198
Although there are multiple return statements in this function body, only one will be executed at a time
More Example
BS (May 2012) 48
#include <stdio.h>int printMenu(char s);
void main(void) { int y; y = printMenu(‘A’); printf(“The return value is: %d”, y);}
int printMenu(char s) { int x=99; if (x > 90) { printf(“This program draws %c rectangle\n”, s); return x; } else return x*2;}
#include <stdio.h>int printMenu(char s);
void main(void) { int y; y = printMenu(‘A’); printf(“The return value is: %d”, y);}
int printMenu(char s) { int x=99; if (x > 90) { printf(“This program draws %c rectangle\n”, s); return x; } else return x*2;}
main
printMenu
99 or 198 ‘A’
MULTIPLE FUNCTIONS IN A PROGRAM
Topic 4-2
BS (May 2012) 49
Working with Multiple Functions
• This example demonstrates a program with two programmer-defined functions: doA and doB
BS (May 2012) 50
#include<stdio.h> void doA(void); void doB(void);
void main() { int y = 10; doA(); printf(“Main -->%d\n", y); doB(); }
#include<stdio.h> void doA(void); void doB(void);
void main() { int y = 10; doA(); printf(“Main -->%d\n", y); doB(); }
void doA(void) { int a = 10; printf(“A -->%d\n", a*2); a += 3;}
void doB(void) { int b = 30; printf(“B -->%d\n", b); printf(“Done.\n”);}
void doA(void) { int a = 10; printf(“A -->%d\n", a*2); a += 3;}
void doB(void) { int b = 30; printf(“B -->%d\n", b); printf(“Done.\n”);}
A -->20Main -->10B -->30Done
main
doA doB
More Example• This example demonstrate a program with two programmer-
defined functions that each returns a value to the caller.
BS (May 2012) 51
#include<stdio.h> int doA(void); float doB(void);
void main() { int y=10; float s; y = doA(); s = doB(); printf(“Main -->%d “ “%.2f\n", y, s); }
#include<stdio.h> int doA(void); float doB(void);
void main() { int y=10; float s; y = doA(); s = doB(); printf(“Main -->%d “ “%.2f\n", y, s); }
int doA(void) { int a=10; printf(“A -->%d\n", a*2); return (a+3);}
float doB(void) { float b=30.0; printf(“B -->%.2f\n", b); return (b+2.5);}
int doA(void) { int a=10; printf(“A -->%d\n", a*2); return (a+3);}
float doB(void) { float b=30.0; printf(“B -->%.2f\n", b); return (b+2.5);}
main
doA doB
A -->20B -->30.00Main -->13 32.5
13
32.5
More Example• This example demonstrate a program with two programmer-
defined functions that each returns a value to the caller.
BS (May 2012) 52
#include<stdio.h> int doA(void); void doB(int t);
void main() { int y=10; y = doA(); printf(“Main -->%d\n", y); doB(y); }
#include<stdio.h> int doA(void); void doB(int t);
void main() { int y=10; y = doA(); printf(“Main -->%d\n", y); doB(y); }
int doA(void) { int a=10; printf(“A -->%d\n", a*2); return (a-2);}
void doB(int t) { int b=30; b += t; printf(“B -->%d\n", b); }
int doA(void) { int a=10; printf(“A -->%d\n", a*2); return (a-2);}
void doB(int t) { int b=30; b += t; printf(“B -->%d\n", b); } main
doA doBA -->20Main -->8B -->38
88
More Example• This example demonstrates a program with three
programmer-defined functions: doA, doB and doC
BS (May 2012) 53
#include<stdio.h> void doA(void); char doB(int s); int doC(char x);
void main(void) { int r; float t; doA(); t=doB(3); r=doC(t); printf(“%c\n” “%d”, t, r);}
#include<stdio.h> void doA(void); char doB(int s); int doC(char x);
void main(void) { int r; float t; doA(); t=doB(3); r=doC(t); printf(“%c\n” “%d”, t, r);}
void doA(void) { printf(“Welcome!\n”);}
char doB(int s) { printf(“%d\n”,s); return ‘A’; }
int doC(char x){ printf(“%c”, x); return 44;}
void doA(void) { printf(“Welcome!\n”);}
char doB(int s) { printf(“%d\n”,s); return ‘A’; }
int doC(char x){ printf(“%c”, x); return 44;}
Exercise
BS (May 2012) 54
#include <stdio.h>void roof(void);void upper(void);void floor(void);
void main(void){ int x; roof(); for (x=1;x<=3;x++) upper(); floor();}
#include <stdio.h>void roof(void);void upper(void);void floor(void);
void main(void){ int x; roof(); for (x=1;x<=3;x++) upper(); floor();}
void roof(void){ printf(“ ^ \n” “ . . \n” “. .\n”);}
void upper(void){ printf(“------------------\n” “| ----- |\n” “| | | |\n” “| ----- |\n” “------------------\n”);}void floor(void){ printf(“------------------\n” “| |\n” “| |\n” “| ----- |\n” “| | | |\n” “| | | |\n” “------------------\n”);}
void roof(void){ printf(“ ^ \n” “ . . \n” “. .\n”);}
void upper(void){ printf(“------------------\n” “| ----- |\n” “| | | |\n” “| ----- |\n” “------------------\n”);}void floor(void){ printf(“------------------\n” “| |\n” “| |\n” “| ----- |\n” “| | | |\n” “| | | |\n” “------------------\n”);}
main
upperroof floor
OUTPUT?
EFFECT OF LOCAL AND GLOBAL VARIABLES
Topic 4-3
BS (May 2012) 55
Local and Global Variables• Up until now, we have learnt to declare our variables within the braces of
segments (or a function) including the main. They are known as local variables:– Declared within a function and can be accessed inside the function only.– Whenever the function is called, new memory locations will be
created/reserved for the variables.– After leaving the function, they are ‘destroyed’.
• It is also possible to declare variables outside a function. They are called global variables:– Declared outside all functions in a program but can be accessed by all
functions within the program.– While loading the program, memory locations are reserved for these variables
and any function can access these variables for read and write (overwrite) them.
• If there exist a local variable and a global variable with the same name, the compiler will refer to the local variable.
BS (May 2012) 56
Local and Global Variables: The Concept
• A program with functions, and local and global variables may be viewed as one big house with multiple rooms and items. Local items can be directly accessed by occupants of a particular room, while global items can accessed by all occupants in the house. Hence, changes to items in a particular room might have an effect on the room’s occupants only, however changes to items in the hall might affect the occupants of the whole house.
• Similarly, local variables are accessible within a particular function only, while global variables are accessible throughout the program – including the main, and other programmer-defined functions.
• Note that global variables can be changed in any function but local variables can only be changed within the function in which they were declared.
BS (May 2012) 57
Master bedroom
Bedroom #1 Bedroom #2
Hall
Local items
Global items
Global Variables: Example• This program shows the read and write (overwrite) operations to the
global variables• Observe that the use of global variables can simplify the code writing
process (i.e. no value passed between functions via input parameters)
BS (May 2012) 58
#include <stdio.h>
void initialise(void);void getInputs(void);void calSum(void);
int sum, num1, num2;
void main(void){
/* initialise sum to 0 */ initialise( );
/* read num1 and num2 */getInputs( );
calSum( );printf("Sum is %d\n", sum);
}
#include <stdio.h>
void initialise(void);void getInputs(void);void calSum(void);
int sum, num1, num2;
void main(void){
/* initialise sum to 0 */ initialise( );
/* read num1 and num2 */getInputs( );
calSum( );printf("Sum is %d\n", sum);
}
void initialise(void){
sum = 0;}
void getInputs(void){
printf("Enter 2 numbers:");scanf("%d %d",&num1,&num2);
}
void calSum(void){
sum = num1 + num2;}
void initialise(void){
sum = 0;}
void getInputs(void){
printf("Enter 2 numbers:");scanf("%d %d",&num1,&num2);
}
void calSum(void){
sum = num1 + num2;}
Local vs Global Variables: Example
BS (May 2012) 59
#include <stdio.h>// Functions declarationint GetScore(void);void CalculateTotal(int s);void PrintTotal(void);int total = 0;
void main(void) { int Sc, count = 0; for (; count < 10; count++) {
// Functions call Sc = GetScore(); CalculateTotal(Sc); } PrintTotal();}
#include <stdio.h>// Functions declarationint GetScore(void);void CalculateTotal(int s);void PrintTotal(void);int total = 0;
void main(void) { int Sc, count = 0; for (; count < 10; count++) {
// Functions call Sc = GetScore(); CalculateTotal(Sc); } PrintTotal();}
// Functions definitionint GetScore(void) { int temp; printf(“Enter the score: “); scanf(“%d”, temp); return temp;}
void CalculateTotal(int s) {total = total + s;}
void PrintTotal(void) { printf(“Total score is: %d\n”,
total);}
// Functions definitionint GetScore(void) { int temp; printf(“Enter the score: “); scanf(“%d”, temp); return temp;}
void CalculateTotal(int s) {total = total + s;}
void PrintTotal(void) { printf(“Total score is: %d\n”,
total);}
score – local formal parameter
Global variable
Local variable
Global Variables: The Dangerous Side
• Even though the use of global variables promising (can simplify the code writing process), it could also be dangerous at the same time.
• Since any function can have the right to overwrite the value in global variables, a function reading a value from a global variable can not be guaranteed about its validity.
BS (May 2012) 60
#include <stdio.h>void initialise(void);void getInputs(void);void calSum(void);
int sum, num1, num2;
void main(void){
initialise( );
getInputs( );
calSum( );
printf("Sum is %d\n",sum);}
#include <stdio.h>void initialise(void);void getInputs(void);void calSum(void);
int sum, num1, num2;
void main(void){
initialise( );
getInputs( );
calSum( );
printf("Sum is %d\n",sum);}
void initialise(void){
sum = 0;}
void getInputs(void){
printf("Enter 2 numbers:");scanf("%d %d",&num1,&num2);
}
void calSum(void){
sum = num1 + num2;initialise( );
}
void initialise(void){
sum = 0;}
void getInputs(void){
printf("Enter 2 numbers:");scanf("%d %d",&num1,&num2);
}
void calSum(void){
sum = num1 + num2;initialise( );
}
Imagine what would be the output of this program if someone ‘accidentally’ write the following function call inside calSum?
auto AND static STORAGE CLASSES
Topic 4-4
BS (May 2012) 61
Storage Classes of Variables• Local variables only exist within a function by default. When
calling a function repeatedly, we might want to– Start from scratch – re-initialise the variables
• The storage class is ‘auto’– Continue where we left off – remember the last value
• The storage class is ‘static’
• Another two storage classes (seldomly used)– register (ask to use hardware registers if available)– extern (global variables are external)
BS (May 2012) 62
auto vs static Storage Classes
• auto:– The keyword auto explicitly declares variables of automatic storage duration.– Variables with automatic storage duration are created when the block in which
they are declared is entered, exist when the block is active and destroyed when the block is exited.
– By default, local variables have class storage of type auto . The auto keyword is rarely used because:
• is the same as
• static:– By default, all global variables are of type static. Hence, in general it
is not necessary to use the static keyword in their declarations.– However the static keyword can be applied to a local variable so
that the variable still exist even though the program has gone out of the function. As a result, whenever the program enters the function again, the value in the static variable still holds.
BS (May 2012) 63
int a, b; auto int a, b;
Effect of auto and static Statements: Example
BS (May 2012) 64
#include <stdio.h>void autoExample(void);void static_example(void);
void main(void){
int i;
printf("Auto example:\n");
for (i=1; i<=3; i++)autoExample();
printf(“\nStatic example:\n");
for (i=1; i<=3; i++)staticExample();
}
#include <stdio.h>void autoExample(void);void static_example(void);
void main(void){
int i;
printf("Auto example:\n");
for (i=1; i<=3; i++)autoExample();
printf(“\nStatic example:\n");
for (i=1; i<=3; i++)staticExample();
}
void autoExample(void)
{
auto int num = 1;
printf(“ %d\n”,num);
num = num + 2;
}
void staticExample(void){
static int num = 1;
printf(“ %d\n”,num);num = num + 2;
}
void autoExample(void)
{
auto int num = 1;
printf(“ %d\n”,num);
num = num + 2;
}
void staticExample(void){
static int num = 1;
printf(“ %d\n”,num);num = num + 2;
}
Output:
Auto example:111
Static example:135
Summary1. Two categories of functions: built-in or predefined or standard functions
and Programmer-defined functions2. To work with programmer-defined functions, it’s necessary to declare
functions prototypes; call functions; and define Functions3. Four basic types of programmer-defined functions:
– Receive no input parameter and return nothing,– Receive no input parameter but return a value,– Receive input parameter( one or more) and return nothing– Receive input parameter( one or more) and return a value
4. Also, you should have learned about:– Multiple return statements in a function– Working with multiple functions– Effect of local and global variables accessed by functions in a program– Types and effects of auto and static storage classes to local and global
variables
BS (May 2012) 65