You are on page 1of 27

Chapter 7

Functions and Scopes

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 2

Chapter Contents
 Functions
Definition, Declarations and Structure
Using arguments
Exiting the function
Passing information
by value
by reference

 Scope and Visibility


 Lifetime of Variables
 Summary
 Exercises

A function is an autonomous part of a program, designed to


perform a specific task.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 3

Functions - Introduction
 C is a procedural language, based on functions.
 A function is a self-contained unit of program code, designed to
accomplish a particular task.

 Every C program starts executing a function named main( ),


which may call other functions.

 A function can perform actions and return a value.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 4

Functions – Introduction – cont’d


 We use functions for several purposes:
To save repetitions.
To make programs more modular (easier to change and
maintain).
Save work by using functions that have already been written
and tested in other programs.
Readability (avoid ‘spaghetti’ code).

 We shall see:
Definition and declaration of functions.
Invoking functions.
Communicating: passing information to and from functions.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 5

Function Call - Diagram


main()
{
perform_task_1( );
perform_task_2( );
}
task
performed
perform_task_1( )
{
....
}
task
performed
perform_task_2( )
{
...
}
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 6

Function Definition
 Every function in C has the following template:

return_type Function_name(declaration of parameters)

 The first line of a function is called the function header.

 return_type
The type of the value that the function returns.
If no return type is specified, int is the default.
If the function only performs some task and has no value to
return, one should specify void as its return type.

 Parameters:
The parameters are variables that are initialized with values
passed to the function.
A function may have no parameters. In this case the
parentheses are left empty , or the keyword void is
written inside them.
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 7

Function Body
 The function body contains:
Definitions of local variables are optional, but are usually
present.
Executable statements, which may be any statement in C.

 If the function returns a value, the return statement is obligatory.


It may occur in a function more than once.

The syntax is: return (expression);

 The parentheses are optional.

 If the function returns no value, it can still be exited before its’


end, using the syntax : return;

© Copyright: Spymek Software Pvt. Ltd.


A Simple Program – Using
C1 Ch03 - Operators and Expressions – 8

Functions
 Let’s write a program for printing the following header:
******************************
Hello World
******************************
 It is convenient to create a function, typerow( ) , for printing
a row of 30 asterisks.
#include <stdio.h>
void typerow( )
{
int counter;
for(counter = 1 ; counter <= 30 ; ++counter)
putchar('*');
putchar('\n');
}
function return
void main(void)
{
typerow( );
printf(" hello World \n");
typerow( );
} © Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 9

Explanations
 The function typerow() prints 30 asterisks in a row.

 The function performs a constant action. It does not require any


parameters.

 It is invoked twice by calling its name with parenthesis:


typerow();

 When the function has completed its task, it returns to the same
place in the program where it was invoked, and the program
continues.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 10

Called Functions - Diagram


 A diagram describing the called functions during execution:
main( )

typerow( )

putchar( )

printf( )

typerow( )

putchar( )
} © Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 11

Function Parameters
 Let’s rewrite our function typerow( ), so that it will print out a
varying number of whichever char requested by the calling
function. For example, typerow(26, '$'); will result in 26
dollar signs in a row .
void typerow(int number, char ch)
{
int counter;
for(counter = 1; counter <= number ; ++counter)
putchar(ch);
putchar('\n');
}

 The prototype - typerow(int number, char ch); informs


the compiler that typerow() receives an argument of type int
and an argument of type char. An attempt to invoke the function
with other parameters will cause a compilation error.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 12

Example: triangle.c
1 /* triangle.c
2 This program prints a right-angled triangle.
3 The triangle’s size and the character that composes
4 it are determined by the user. */
5
6 #include <stdio.h>
7
8 void typerow(int number, char ch); /* prototype that enables
9 the compiler to check if we send correct Parameters to the
10 function. */
11 void main(void)
12 {
13 int size; /* the size of the triangle*/
14 char ch; /* the char that will compose the triangle*/
15 int i; /* a counter */
16 printf("Enter the triangle’s size => ");
17 scanf("%d",&size);
18 getchar();

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 13

Example: triangle.c – cont’d


19 printf("Of which char should the triangle be built ? "
20 "=> ");
21 scanf ("%c", &ch);
22
23 for(i = 1 ; i <= size; i++)
24 typerow(i, ch);
25 }
26
27 void typerow(int number, char ch)
28 {
29 int counter;
30
31 for(counter=1; counter <= number ; counter++)
32 printf(" %c", ch);
33 putchar('\n');
34 }

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 14

Exiting a Function
 One way to leave a function is with the return statement, as shown
before.
The control returns to the place from which the function was called.
 Another way to leave a function (and the whole program) is with the
function exit.

void exit(int status);

 The function exit() (prototyped in stdlib.h) terminates the


program.
 The return value may be 0 (usually to indicate success), or a non-
zero value (usually to indicate failure).
 The returned value is received by the operating system.
 If written in main(), return and exit() have the same
effect.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 15

Returning a Value From a Function


 abs is a function that returns the absolute value of an integer.
 Intuitively, we want to use the following:
x = abs(a);
 Where a is the argument passed to the function abs(), which
returns the number stripped of any negative sign.
 x is assigned the value returned from that function.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 16
Returning a Value From a
Function- example
1 /* return.c */
2 #include <stdio.h>
3 int abs(int num);
4 void main(void)
5 {
6 int a=10, b=0, c=-22;
7 int x, y, z;
8 x = abs(a);
9 y = abs(b);
10 z = abs(c);
11 printf("%d %d %d\n", x, y, z);
12 }
13
14 int abs(int num)
15 {
16 int absnum;
17 absnum = (num < 0) ? -num : num;
18 return(absnum);
19 }
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 17

Call by Value
 The parameter that was sent from the calling function is called
an ‘actual parameter’. The parameter received by the function is
called ‘formal parameter’ or ‘argument’.

 When sending a variable to a function we ALWAYS send it by


value.

 The parameter that the function receives is a completely new


variable. The only connection between the formal parameter
and the actual parameter is the value : when the formal
parameter is created, it is automatically initialized with the value
of the actual parameter.

 Changes to the formal parameter can’t effect the actual


parameter, since they are absolutely not connected, each of
them having its own address in the computer’s memory.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 18

Call by Reference
 Sometimes we want the parameter that was sent to a function to
be changed by that function.

 When passing a variable by reference it’s address is passed,


rather than it’s value, and so the called function can change the
variable’s value.

 To understand call by reference we should first


understand pointers.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 19

Call by Value vs. Call by Ref.

By Value By Reference
The value of the actual parameter Any change to the formal
is not changed (even if the formal parameter is reflected in the
parameter is changed). actual parameter.
Argument may be any expression :
Argument must be an
-3, i, 2 * a + b, -123,
address of a variable.
8.23, sqrt(abs(n)) .

 If the argument is a scalar (simple) variable, it is passed by


value ( this is the default). We shall later see how call by
reference is implemented with an argument which is a scalar
variable.
 If the argument is an array it is always passed by reference.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 20

Example: Swap values

void main(void)
{
int num1 = 10, num2 = 20;

printf(“num1 = %d num2 = %d ”,num1,num2) ;

swap( &num1, &num2 );

printf(“num1 = %d num2 = %d ”,num1,num2) ;

void swap( int * num1, int * num2 )


{
int temp;

temp = *num1;
*num1 = *num2;
*num2 = temp;

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 21

Scope and Life Time of Variables


 The scope of a variable is the part of the program in which the
variable is visible (i.e. may be used ).

 The life time of a variable is the time between the ‘birth’ of the
variable on the computers memory and the time it ‘dies’.

 There are two broad classifications of scope:

Global scope : global.


Block (local) scope : automatic local, static local.

 The table in the next page describes the attributes of global and
automatic local variables. The two static types will be discussed
later.

© Copyright: Spymek Software Pvt. Ltd.


Global vs. Automatic Local
C1 Ch03 - Operators and Expressions – 22

– cont’d
Global Automatic Local
declaration outside any function in a block { }
Unless specified
No automatic initialization.
otherwise,
initialization automatically initialized If specifically initialized - it
occurs at each ‘birth’
to 0
functions beneath it, in
scope its block
the same module
each time the block is
‘birth’ once, before main()
entered
once, after main() each time the block is
‘death’ ends exited
address on the data area on the stack area

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 23

Scope Diagram
1 int num = 42;
2 void func(void)
3 {
4 int other_num = 10;
5 printf ("%d %d", num, other_num);
6 }
7 void main()
8 {
9 int num = 1, other_num = 2;
10 printf ("%d %d", num, other_num);
11 {
12 int other_num = 3;
13 printf ("%d %d", num, other_num);
14 }
15 printf ("%d %d", num, other_num);
16 func();
17 }

 When referencing a variable, the compiler searches for such a


variable name within the immediate scope.
 If not found, then the next “higher” scope is searched.
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 24

Global Variables – Bad News


 Global variables are not healthy for your program,
try to avoid them.

 Global variables are ‘exposed’. It is hard to predict the contents


of a global variable, since many functions can change it.

 It captures memory (on the data) throughout the lifetime of the


program.

 The behavior of a function should be predicted, by the


arguments that it gets. If the functions behavior also depends on
a global variable, it is not as independent as it should be.

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 25

Storage Classes

Auto Register Static Extern


Keyword auto register static extern
Within a
Scope Local Local Within a file
function
Within a Within a Through Through
Life
function function out prg out prg
Initial Garbage Garbage Zero Zero
Value
Memory On stack Data Data
Registers
Section Section

© Copyright: Spymek Software Pvt. Ltd.


C1 Ch03 - Operators and Expressions – 26

Summary
 A Function is an autonomous code segment that accomplishes a
particular task.
 A function may receive parameters and may return a value.
 Actual parameters – sent.
Formal parameters (arguments) – received.
 Variables may be passed as parameters to a function :
By value:
The value of the variable is passed.
Changing the formal parameter does not effect the actual
parameter. Scalar variables are sent this way by default.

By reference
The address of the variable is passed.
Changing the formal parameter does effect the actual
parameter. Arrays can only be sent this way.
© Copyright: Spymek Software Pvt. Ltd.
C1 Ch03 - Operators and Expressions – 27

Summary – cont’d
 There are 4 storage classes :
Automatic
Static
Register
extern
 The arguments received by a function are automatic local
variables of that function.
 A program should be split to several modules.
 The keyword extern help sharing global variables or functions
between different modules of the program.

© Copyright: Spymek Software Pvt. Ltd.

You might also like