[go: up one dir, main page]

0% found this document useful (0 votes)
34 views68 pages

C Programming: Functions and Modular Programming

Uploaded by

Shilin Zhang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views68 pages

C Programming: Functions and Modular Programming

Uploaded by

Shilin Zhang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

From Computational Thinking to Programming Part II

Presented by

Edwin Teo Hang Tong


School of Electrical and Electronic Engineering

Office: S2-B2b-67
Email: htteo@ntu.edu.sg
Ph.: 67906371

1
What you should know by now
Computer Hardware Basics
 CPU, ALU, memory types, input, display methods…etc
 C language Overview
 How what you code is translated into something the system can
understand and operate on
 Basic C operators
 specific symbols recognized by C to mean something, usually its for
performing a stated action onto one or many objects (or variables)
 Standard Library functions
 Collection of instructions stored into a “library” to be called up so more
specialised operators can be used.
 How decision making is done
How C “thinks” though logic algebra.
The use of if-else, for, while loops…etc
3
What you will learn from now
Functions
• How to make your own functions and use them effectively
 Modular Programming
• Organization of your code using compartmentalization
 Pointers
• Send information via address referencing
 Arrays
• How to define Arrays, inset values to them and operate on
them

4
FUNCTIONS

4
Functions
Why the need for functions?
 Break large problem down into smaller sub‐tasks
 An easier way to solve complex problems
 Make a program much easier to read and maintain (hide unnecessary details)
 Generalize a repeated set of instructions
 don’t have to keep writing the same thing over and over
 printf and scanf are good examples
 Often, solution to sub problems can be reused (e.g. common libraries)
 Easier for debugging
 Allow team based projects

5
From Dilbert by Scott Adams
What is a function?
 a group of declarations and statements that 
is assigned a name
 Effectively, a named statement block
 Usually has inputs and an output value

 it is a sub‐program (also known as sub‐routine)
 in C programs we always define a function named main
 main( ) is just another function
 inside main we can call other functions
 Which themselves can call other functions, and so on…

Hint : Think of functions as individual standalone programs that can be called upon by 
other functions (or the main program) to do specific tasks.  6
Functions
num_1,  main num_1, 
num_2  num_2 
sub add

add_value

sub_value

msg

7
Rules of Functions in C
 Syntax
 Function declaration (or prototype) 
 Function definition
 Function call (or reference or 
invocation)

8
Function declaration (prototype)

 The function must be declared before it is used 


for the first time
 Some software projects in C are composed of 
more than one file. In this case, we want to be 
able to define the function in one file, and to 
use it in all files.
 The function has to be declared in every file in 
which it is used.

9
 Function declaration (prototype) includes 3 parts:
 return type (function can only return 1 variable or non at all)
 function name
 types and names of parameters                                 
(however, names are optional)

return_type function_name (parameter‐list);


where parameter‐list:
(type1 para1, type2 para2, . . . . )  or  (void)
Example : int func1(double, int);
void func2(int a, int b);
10
#include <stdio.h>
int add (int a, int b);
int sub (int, int );
void msg (void);

num_1,  main num_1, 


num_2  num_2 
sub add

add_value

sub_value

msg

11
Function definition – 4 parts

return_type function_name (formal  parameter‐list)


{
variable declarations ;
statements ; Body
return return_value ;
}

Example:
double cube (double a) double cube (double a)
{ alternatively {
double b=0; return a*a*a;
b= a*a*a; }
return b;
}

12
#include <stdio.h>
int add (int a, int b);
int sub (int, int );
void msg (void);

num_1,  int main (void) num_1, 


num_2  { int num_1, num_2; num_2 
int sub (int a, int b) printf(….); int add (int a,int b)
{ int c; scanf(….); {
c = a‐b; …. return a + b;
if (c <=0) …. }
…. ….
else return 0; } add_value
return c;
} sub_value

void msg (void)
{
printf (“This is an error”);
}

13
Function Call
 Multiple ways to invoke function.
 In general it takes the form of function_name(argument list)
 Examples:
I. func1();
II. num1 = func2();
III. num1 = func3(num2);
IV. num1 = func4(num2, num3);
V. printf(“ The number is %d”, func5(num1);

I. Call func1 where func1 does NOT take in arguments and does not return 
value.
II. Call func2 with no arguments but return value to num1.
III. Call func3 with 1 argument and send back 1 value into num1.
IV. Call func4 that takes in 2 arguments and return 1 value into num1.
V. Call func5 that takes in 1 argument and return 1 value to be printed as an 
integer.

14
Parameter list correspondence
int i, j;
int power (int x, int m)
int k; {
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
i=6; }
j=7;
k =power (i, j);
double sinc (double x)
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ {
double new_x=0,y; ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ }
y = sinc(new_x);
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ match in Number, Order, Type (N.O.T)

15
#include <stdio.h>
int add (int a, int b);
int sub (int, int );
void msg (void);

num_1,  int main (void) num_1, 


num_2  { int num_1, num_2;  num_2 
int sub (int a, int b) int add_value, sub_value; int add (int a,int b)
{ int c; printf(….); {
c = a‐b; scanf(….);
return a + b;
if (c <=0) if (num_1 <0||num_2<0)
{msg(); }
{msg();
return 0;}
return 0;}
add_value=add(num_1, num_2);
else sub_value=sub(num_1, num_2); add_value
return c; If (sub_value==0) return 0;
} sub_value
printf(…);
return 0; }

msg
void         (void)
{
printf (“This is an error”);
}

16
Function Call for cube
double cube (double a); Function declaration
int main (void)
{
double num = 0.0, numcubed = 0.0;
printf(“Enter a number\n”); Here is where we call or
scanf(“%lf”,&num); reference the function
numcubed = cube (num); cube
printf(“%f cubed is %f\n”, num, numcubed);
return 0 ;
}

double cube (double a) Function definition
{ This is a function 
return a * a * a;
} defined outside main
17
Multiple function calls
#include <stdio.h>
double cal_area(double);
double cal_circum(double);

int main (void)
{
double rad, area;
printf("Please key in radius of circle in radian ");
scanf("%lf", &rad);

area = cal_area(rad);
printf("The area of the circle with radius %lf is %lf and circum is %lf", rad, area, cal_circum(rad));
return 0;
}

double cal_area(double a)
{
return a*a*3.14;
}

double cal_circum(double rad)
{
return 2*rad*3.14;
} 15
Declarations for Library Functions

 stdio.h actually contains a large set of function 
declarations.
 The #include directive tells the compiler to insert 
these declarations into the source program, so that 
these functions could be called.

 Similarly, math.h, ctype.h etc. may be included, if 
required.

19
RE‐Cap
• Prototype 
– int Area_square(int, int);
• Function Call
– printf(“The area of the square is %d”, Area_square(4,5));
• Function definition
– int Area_square (int x, int y)
{ return x * y;}
• A function can have many parameters but only 1 
return value (or void)

20
Continual Assessment II 
 15% of Final Course Mark.
 CA occurs during Tutorial & Practical Lesson 10.

• Coverage: From Tutorial 1 to Tutorial 9


• Programming‐based
• Reminder:
– Attendance is compulsory
– Remember to bring Matric card for attendance taking.
– Those absent without valid MCs will get ZERO mark.
– Those absent with VALID reasons need to get back to Tutor within 1
week’s time to arrange makeup.
• Check Announcement at NTUlearn for any updates.

21
How to pass information to functions
Pass‐by‐value vs Pass‐by‐reference
 pass‐by‐value 
 Actual parameters (arguments) are passed by value
 i.e. “Local Copies” of parameter values are passed to 
the functions
 Duplicates the actual “values” of the parameter to be 
passed to the function 
 pass‐by‐reference 
 Pass‐by‐reference is done by passing pointers
(covered later)
 Actually copy the variable/parameter’s addresses
 Send over the address or “location” of the 
parameter/variable to the function  22
Pass by Value 
 Features of pass‐by‐value 
 Casting of Arguments
 Arguments to functions are converted to the parameter types 
specified in the prototype if they (the arguments) are not of 
the type specified.
 return expression 
• Use to pass back 1 value to the calling function.
 void functions and void parameter list
• Not all arguments expects arguments and not all functions 
will give a return value back to its calling function.
 Scope and lifetime of variables
• Where the variable is declared will affect its influence and 
when it will be terminated.

23
#include <stdio.h>
int add (int a, int b); Casting of Arguments 
int sub (int, int );
void msg (void);

int main (void) 3, 4


num_1,  3.2
{ doublenum_1, num_2; 
num_2  4.7
int sub (int a, int b) int add_value, sub_value; int add (int a,int b)
{ int c; printf(….);
scanf(….); {
c = a‐b; return a + b;
add_value=add(num_1, num_2);
if (c <=0) sub_value=sub(num_1, num_2); }
{msg(); …
return 0;} return 0; }
else int
return c;
} sub_value

msg
void         (void)
{
printf (“This is an error”);
}

21
Casting of Arguments: int max (int x, int y);
int main ()
{
int num_x=3, num_y=8, max_val;
double f1=2.8, f2=2.6;
‐‐‐
max_val =max (num_x, num_y);
‐‐‐
Function inputs are integers.
max_val = max (f1, f2);
Therefore, arguments will be
‐‐‐
type casted.
}
int max (int a, int b)
a b max_val
{ if (a>b)
return a ; 3 8 8
else
return b ; 2 2 2
}
25
Pass by Value 
 Features of pass‐by‐value 
 Casting of Arguments
 Arguments to functions are converted to the parameter types 
specified in the prototype if they (the arguments) are not of 
the type specified.
 return expression 
• Use to pass back 1 value to the calling function or 
termination of function.
 void functions and void parameter list
• Not all arguments expects arguments and not all functions 
will give a return value back to its calling function.
 Scope and lifetime of variables
• Where the variable is declared will affect its influence and 
when it will be terminated.
26
Function – output thru return
 Function can return one value (or no value)
 return statement
□ return ; 
causes the execution of the function to terminate
□ return expression;
 The evaluated value of expression is returned 
 The type of the value returned must be the same as 
the return_type defined for the function (or a ‘lower’ 
type)

27
void Functions
 Sometimes, it is not necessary for a function to  
return a value.
 In these cases, the function return_type should be 
void and no value should be returned.
 Use of the return keyword within such a function 
would exit the function immediately. 
 Use of return in a void function is optional.

28
#include <stdio.h>
int add (int a, int b);
int sub (int, int );
void msg (void);

num_1,  int main (void) num_1, 


num_2  { int num_1, num_2;  num_2 
int sub (int a, int b) int add_value, sub_value; int add (int a,int b)
{ int c; printf(….); {
c = a‐b; scanf(….);
return a + b;
if (c <=0) if (num_1 <0||num_2<0)
{msg(); }
{msg();
return 0;}
return 0;}
add_value=add(num_1, num_2);
else sub_value=sub(num_1, num_2); add_value
return c; If (sub_value==0) return 0;
} sub_value
printf(…);
return 0; }

msg
void         (void)
{
printf (“This is an error”);
}

29
Example of void function
#include <stdio.h>
double cal_area(double a)
double cal_area(double);
{
void wrong_value(void);
return a*a*3.14;
int main (void)
}
{
double rad, area_cir; void wrong_value(void)
printf("Please key in radius of circle in radian "); {
scanf("%lf",&rad); printf("This value cannot be accepted 
please try again\n");
while (rad<=0) }
{
wrong_value();
printf("Please key in radius of circle in radian ");
scanf("%lf",&rad);
}
area_cir =cal_area(rad);
printf("The area of the circle with radius %lf is 
%lf", rad,area_cir);
return 0;
}
30
Pass by Value 
 Features of pass‐by‐value 
 Casting of Arguments
 Arguments to functions are converted to the parameter types 
specified in the prototype if they (the arguments) are not of 
the type specified.
 return expression 
• Use to pass back 1 value to the calling function or 
termination of function.
 void functions and void parameter list
• Not all arguments expects arguments and not all functions 
will give a return value back to its calling function.
 Scope and lifetime of variables
• Where the variable is declared will affect its influence and 
when it will be terminated.
31
Scope & Lifetime of variables
• A variable is a location in storage (memory).   It has
‐ Scope ‐ Region of program in which the declaration is active (can be 
accessed)
‐ Block, Function, File, Prototype….
‐ The scope for an identifier  (name of variable) is determined by 
where it is declared.

‐ Storage Duration ‐ Determines the lifetime of the variable 
‐ There are 4 storage duration for variables: static, automatic,
allocated and thread (c11).
Storage‐class specifiers
Specifier Function
auto Local automatic variable
static Static variable
register Register variable
extern External variable
typedef Form more complex types 32
Scope of variables
• File Scope – Active region begins at the declaration and ends only at the end of the source code.
 i.e. can be accessed by all functions in the program!!!
• variables declared outside and before the body of any function has file scope.
 i.e. declared at the same level as function prototypes.
• In general, variables with file scope are commonly known as global variables.
#include <stdio.h>
int func1(int, int); G1 is a global variable and 
int G1= 10;
has scope from here to
int main(void)
{   
int L1, L2=5;
printf("Combined G = %d\n", G1); 10
for(L1=0;L2>0;L2‐‐)
{   
int B1=2;
L1 += B1 + G1;
}
printf("L1 =%d \n",L1); 60
printf("function returns %d \n", func1(L1, L2)); 70
return 0;
}

int func1(int a, int b)


{
return a+b+G1; 33
} HERE!
Scope of variables
• Function Scope – Active region is only within the function the variable is defined.
 i.e. can only be accessed in the function it is declared in.
• variables declared within the body of the function has function scope.
• In general, variables with function scope are commonly known as local variables (localized to the 
function).
#include <stdio.h>
int func1(int, int);
int G1= 10;

int main(void)
{   
int L1, L2=5;
printf("Combined G = %d\n", G1);
for(L1=0;L2>0;L2‐‐)
{   
int B1=2; L1 and L2 has 
L1 += B1 + G1; function scope within 
} main()
printf("L1 =%d \n",L1);
printf("function returns %d \n", func1(L1, L2));
return 0;
}

int func1(int a, int b)


{ a and b has function 
return a+b+G1; scope within func1() 31
}
Scope of variables
• Block Scope – Active region is within the statement block defined by { and }. 
• variables declared within a statement block have Block scope.
• Examples of statement blocks are loops (for, while…) and decision statement 
(switch, if‐else…) or any other statements encased in { and }. 
#include <stdio.h>
int func1(int, int);
int G1= 10;

int main(void)
{   
int L1, L2=5;
printf("Combined G = %d\n", G1);
for(L1=0;L2>0;L2‐‐)
{    B1 has block scope and is 
int B1=2;
L1 += B1 + G1; active only between its { and 
} }.
printf("L1 =%d \n",L1);
printf("function returns %d \n", func1(L1, L2));
return 0;
}

int func1(int a, int b)


{
return a+b+G1; 35
}
Scope Rules 
• What happens when program uses the same identifiers for different variables  
with different scopes?
• Function supersedes file.
• Blocks supersedes functions.
• Inner block supersedes outer blocks. 

 A variable declared within a function (local variable) 
is unrelated to variables declared elsewhere, even if 
they have the same name
 A function cannot access variables that are declared 
in other functions

36
Scope Rules 
• What happens when program uses the same identifiers for different variables  
with different scopes?
• Function supersedes file.
• Blocks supersedes functions.
• Inner block supersedes outer blocks. 
int main(void)
{
#include <stdio.h>
int G1=1;
int func1(int);
int L1,L2=5;
int func2(int);
for(L1=5;L2>0;L2‐‐)
int G1=10, G2=5;
{
int B1=10;
if(L2>3)
{
int B1=100;
int func1(int a) {
{ int B1=1000;
return a + G1; L1 += B1;
} }
int func2(int a) L1 += B1;
{ }
int G2=10; L1 += B1;
return a+ G2; }
} printf("L1 =%d \n",L1);
printf("Total = %d\n",func1(G1)+func2(G2));
return 0;
} 36
Scope Rules 
• What happens when program uses the same identifiers for different variables  
with different scopes?
• Function supersedes file.
• Blocks supersedes functions.
• Inner block supersedes outer blocks. 

int G1=10, G2=5; Scope Identifier Value
On screen Global G1 10
int main(void)
Total = 26
{ Global G2 5
int G1=1;
… main          G1                 1
printf(" Total = %d\n",func1(G1)+func2(G2)); func1         a                    1 
return 0;
} func2         a                     5 
int func1(int a) 11 func2         G2                  10 
{     return a + G1;    }

int func2(int a)
{   int G2=10; 15
return a+ G2;       }
38
Scope Rules 
• What happens when program uses the same identifiers for different variables  
with different scopes?
• Function supersedes file.
• Blocks supersedes functions.
Scope Identifier Value
• Inner block supersedes outer blocks. 
… main L1 5
int L1,L2=5;
for(L1=5;L2>0;L2‐‐) Block 1
main L2 5
{ Block 1 B1 10
int B1=10;
if(L2>3)
{
int B1=100;
{
int B1=1000;
L1 += B1;
}
L1 += B1;
}
L1 += B1;
}
printf("L1 =%d \n",L1); 39

Scope Rules 
• What happens when program uses the same identifiers for different variables  
with different scopes?
• Function supersedes file.
• Blocks supersedes functions.
Scope Identifier Value
• Inner block supersedes outer blocks. 
… main L1 5
int L1,L2=5;
for(L1=5;L2>0;L2‐‐) Block 1
main L2 5
{ Block 1 B1 10
int B1=10;
if(L2>3) Block 2 Block 2 B1 100
{
int B1=100;
{
int B1=1000;
L1 += B1;
}
L1 += B1;
}
L1 += B1;
}
printf("L1 =%d \n",L1); 39

Scope Rules 
• What happens when program uses the same identifiers for different variables  
with different scopes?
• Function supersedes file.
• Blocks supersedes functions.
Scope Identifier Value
• Inner block supersedes outer blocks. 
… main L1 5
int L1,L2=5;
for(L1=5;L2>0;L2‐‐) Block 1
main L2 5
{ Block 1 B1 10
int B1=10;
if(L2>3) Block 2 Block 2 B1 100
{ Block 3 B1 1000
int B1=100; Block 3
{
int B1=1000;
L1 += B1;
}
L1 += B1;
}
L1 += B1;
}
printf("L1 =%d \n",L1); 39

Scope Rules 
• What happens when program uses the same identifiers for different variables  
with different scopes?
• Function supersedes file.
• Blocks supersedes functions.
Scope Identifier Value
• Inner block supersedes outer blocks. 
… main L1 1005
int L1,L2=5;
for(L1=5;L2>0;L2‐‐) Block 1
main L2 5
{ Block 1 B1 10
int B1=10;
if(L2>3) Block 2 Block 2 B1 100
{ Block 3 B1 1000
int B1=100; Block 3
{
int B1=1000;
L1 += B1;
}
L1 += B1;
}
L1 += B1;
}
printf("L1 =%d \n",L1); 39

Scope Rules 
• What happens when program uses the same identifiers for different variables  
with different scopes?
• Function supersedes file.
• Blocks supersedes functions.
Scope Identifier Value
• Inner block supersedes outer blocks. 
… main L1 1105
int L1,L2=5;
for(L1=5;L2>0;L2‐‐) Block 1
main L2 5
{ Block 1 B1 10
int B1=10;
if(L2>3) Block 2 Block 2 B1 100
{ Block 3 B1 1000
int B1=100; Block 3
{
int B1=1000;
L1 += B1;
}
L1 += B1;
}
L1 += B1;
}
printf("L1 =%d \n",L1); 39

Scope Rules 
• What happens when program uses the same identifiers for different variables  
with different scopes?
• Function supersedes file.
• Blocks supersedes functions.
Scope Identifier Value
• Inner block supersedes outer blocks. 
… main L1 1115
int L1,L2=5;
for(L1=5;L2>0;L2‐‐) Block 1
main L2 5
{ Block 1 B1 10
int B1=10;
if(L2>3) Block 2 Block 2 B1 100
{ Block 3 B1 1000
int B1=100; Block 3
{
int B1=1000;
L1 += B1;
}
L1 += B1;
}
L1 += B1;
}
printf("L1 =%d \n",L1); 39

Scope Rules 
• What happens when program uses the same identifiers for different variables  
with different scopes?
• Function supersedes file.
• Blocks supersedes functions.
Scope Identifier Value
• Inner block supersedes outer blocks. 
… main L1 2255
int L1,L2=5;
for(L1=5;L2>0;L2‐‐) Block 1
main L2 0
{ Block 1 B1 10
int B1=10;
if(L2>3) Block 2 Block 2 B1 100
{ Block 3 B1 1000
int B1=100; Block 3
{
int B1=1000;
L1 += B1;
}
L1 += B1;
}
L1 += B1; On screen
} L1 = 2255
printf("L1 =%d \n",L1); 39

Scope Rules:
Active Variables can be changed!
#include <stdio.h>
void func ( ) ;
int i = 4 ;                /*Globally declare and initialize*/

int main ( )
{
i++ /*global variable declared above */
func ( ) ;
return 0 ; i = 5
}

void func ( )
{
int y=10; /*Internally declare and initialize */
y=i +y;
}  y = 4 + 10  y = 5 + 10 
46
Scope Rules:
Initialization requirements 
• Variables with file scope (global variable) is self‐initialized 
by the system during declaration.
 i.e. global variables that are NOT initialized have a 
default value. 
Data Type Initialization
int 0
char ‘\0’
float 0.0
pointer NULL

• HOWEVER, local variables (function, block scope…) MUST 
be initialized before they can be used.
47
Scope Rules:
Initialization requirements (Example) 


int G1, G2; Scope Identifier Value
On screen Global G1 0
int main(void)
Total = 11
{ Global G2 0
int G1=1;
… main          G1                 1
printf(" Total = %d\n",func1(G1)+func2(G2)); func1         a                    1 
return 0;
} func2         a                     0 
int func1(int a) 1 func2         G2                  10 
{     return a + G1;    }

int func2(int a)
{   int G2=10; 10
return a+ G2;       }
48
Reminder on arguments and variables
• Local variables & function arguments have scope of the 
function in which they’re defined
 Thus, local variables AND parameters can supersede 
global variables using the same name.
int a ;
int b ;

int f (double a)
{
double b ;
b = a + 2 ;

}

49
Quick Example 1: times7‐ multiply by 7
int times7 (int b)
main ( ) memory
int main (void)
a b
{
1
7
int a = 34, b = 1;
a = times7 (b);
times7 ( ) memory
printf(“a = %d, b = %d\n”, a, b);
return 0; b

} 7

int times7 (int b)
{
b = b * 7;
return b;
}
51
Quick Example 2: Error!!!!: Add Two
int plus_two (int b);
int main (void)
{
int a = 34,  b = 1;
plus_two (b);
printf (“a = %d, b= %d\n”, a, b);
return 0 ;
error:’a’: undeclared identifier
}
Compilation error!
int plus_two (int b) a is declared in main
{
a = b + 2; (undeclared in function!)
}

51
Quick Example 3 
int main (void)
{ Entered main
int subfunc (void)
int sub = 0, a=34;
{ In main, a=34
int a;
printf(“Entered main\n”); Entered subfunc
printf (“Entered”
printf(“In main, a=%d\n”,a);
“subfunc\n”); In subfunc, a=7
a=7;
sub = subfunc ( );
printf(“In subfunc, Exiting subfunc
a=%d\n”,a);
printf (“subfunc returned” subfunc returned 7
“%d\n”, sub);
printf(“Existing” In main, a=34
printf(“In main, a=%d\n”,a);
“subfunc\n”);
return a; Exiting main…
printf (“Exiting main…\n”);
}
return 0 ;
}
a in main and a in subfunc
52
have different scope !
A reminder on Pass‐by‐value

 Here arguments are passed to the function by 
copying their values rather than giving the function 
direct access to the actual variables.

 A change to the value of a variable inside function 
will not change the variable values in the calling 
function.

53
Practice question!
(Hint: You can take 10 mins or 10 secs to solve this) 
#include <stdio.h>
int func1(int, int, int);
int func1(int a, int b, int c)
int func2(int, int);
{
void func3(int);
return a + b + c + G1 + G2;
int G1,G2=10;
}
int func2(int a, int b)
int main(void)
{
{
int G2=3;
int G2=100;
G1=2;
G2 += func1(G1, G2, func2(G2, G1));
return a + b + G1 +G2;
for(;G1>0;G1‐‐)
}
{
void func3(int a)
int G1=4;
{
G2 = G1;
G1=a;
}
}
printf("G2 =%d \n",G2);
return 0;
}
54
Re‐cap
• Pass by value
– Casting of Arguments 
– Functions can return 1 or no value back to its 
caller (void functions)
– Return value through the “return expression”
– Scope of variables (File, Function, Block) 

55
Scope & Lifetime of variables
• A variable is a location in storage (memory).   It has
‐ Scope ‐ Region of program in which the declaration is active (can be 
accessed)
‐ Block, Function, File, Prototype….
‐ The scope for an identifier  (name of variable) is determined by 
where it is declared.

‐ Storage Duration ‐ Determines the lifetime of the variable 
‐ There are 4 storage duration for variables: static, automatic,
allocated and thread (c11).
Storage‐class specifiers
Specifier Function
auto Local automatic variable
static Static variable
register Register variable
extern External variable
typedef Form more complex types 56
Lifetime of variables
• Storage duration or lifetime of variables refers to how long 
the variable exists in the program or how long an identifier 
actually holds the data.

• Storage duration of variables are determined by its storage 
class.
– The storage class of variables are assigned by default through 
the location of  the declaration BUT can also be assigned 
through storage‐class specifiers as well. 

For this course we are only interested in the below!

Specifier Function
auto Local automatic variable
static Static variable

57
auto
• Memory for auto variables are de‐allocated on 
completion of program block (i.e functions or 
statement blocks). 
 i.e. Once function or statement block is done (code 
reaches the “}”), the variable is no longer in valid. 

• auto is the default storage class for local variables
• Since it’s the default class for local variables, its 
seldom necessary to use it. 

{
int count ;
auto is optional auto int day ;
}
58
static
• static class variables retain their value even after statement blocks its 
declared in have been terminated. 
 i.e. the value of a static local variable will always be stored until the end of the 
entire program.
 This does NOT mean the stored value cannot change!!!! Rather the memory 
allocated to the variable is reserved till the end of the program.  
• Local variables if classed as static could then keep their value over different 
function calls, loops, decision cycles…etc
• Static local variable is set to the initialized value only the first time the block 
is entered and MUST be a constant.
• Static class variables have default values during declaration
 i.e. Static class variables have specific values in them even without initialization.
• The default storage class for global variables is commonly referred to as 
static class. (Not entirely true since default linkage is external) 
Outside  course 
syllabus 59
Lifetime of variables:
Example 1 s is 6 and count is 9

s is 6 and count is 8
void func1 (void) ;
int count = 10; /* Global variable */ s is 6 and count is 7
int main (void) s is 6 and count is 6
{
s is 6 and count is 5
while (count‐‐) func1( );
return 0; s is 6 and count is 4
} s is 6 and count is 3
void func1 (void)
s is 6 and count is 2
{    int s = 5;  auto
/*           local variable */
s++ ; s is 6 and count is 1
printf(“s is %d and count is %d\n” , s, count) ; s is 6 and count is 0
}
61
Lifetime of variables:
Example 1 s is 6 and count is 9

s is 7 and count is 8
void func1 (void) ;
int count = 10; /* Global variable */ s is 8 and count is 7
int main (void) s is 9 and count is 6
{
s is 10 and count is 5
while (count‐‐) func1( );
return 0; s is 11 and count is 4
} s is 12 and count is 3
void func1 (void)
s is 13 and count is 2
{   static int s = 5;  static
/*           local variable */
s++ ; s is 14 and count is 1
printf(“s is %d and count is %d\n” , s, count) ; s is 15 and count is 0
}
61
Explanation for example 1 
• static s is local to func1 ‐ initialized when program execution 
begins
‐ Initialization is done only once
• Its value is NOT reset on every invocation of func1
‐ Retain value between function calls
• static variables
‐ Lifetime is like for global variables
‐ Auto‐initialized to 0 if initialization is omitted (like  
global variables)

62
Lifetime of variables:
Example 2
• Counts the number of times the function is called

This is optional
void num_times ( )   as default is 0.

{
static int count = 0 ;  /* set to 0 only first time! */
count++ ;
printf (“count = %d\n”, count ) ;
}

63
Lifetime of variables: Example 3
#include <stdio.h>
int func1(int, int);
int G; Default value = 0

int main(void)
{
Casting!!!
double L1=3.7;
printf("%.2lf , %d", L1, func1(G,L1));
return 0;
} On Screen

int func1(int a, int L1) a = 0, L1 = 3 3.70 , 33


{
for(;L1>0;L1‐‐)
a=0, L1=10
{
static int L1=10;
a=10, L1=11
a += L1++;
a=21, L1=12
}
a=33, L1=13 
return a;
}
64
Summary on Local auto Variable & Scope
• Declaration of variables may follow the left brace that 
introduces a group of statements (nested block), not just at 
beginning of function.
• Variable remain in existence until matching right brace.
• Variables declared at the top of a block have the scope of the 
block.
• The variable in the nested block hides the variable in the 
outer block having the same name. 
o A local variable is visible within nested blocks unless a 
variable with the same name is defined within the nested 
block.
• Local variable initialized in a block is initialized each time it 
enters the block. 65
Summary on Local static Variable & Scope
• Declaration of variables may follow the left brace that introduces a 
group of statements (nested block), not just at beginning of 
function.
• Variables have default values upon declaration.
• Variable remain in existence throughout entire programme.
• Variables declared at the top of a block have the scope of the 
block.
• The variable in the nested block hides the variable in the outer 
block having the same name. 
o A local variable is visible within nested blocks unless a variable 
with the same name is defined within the nested block.
• Local variable initialized in a block is initialized only once, on the 
first entry into the block. 
66
Example 4
#include <stdio.h> #include <stdio.h> #include <stdio.h>

int main(void) int main(void) int main(void)


{ { {
int A=5, B=0; int A=5, B=0; int A=5, B=0;
for(;A>0;A‐‐) for(;A>0;A‐‐) for(;A>0;A‐‐)
{ { {
int A = 3; static int A = 3; static int A = 3;
for(;A>0;A‐‐) for(;A>0;A‐‐) for(;A>0;A‐‐)
{ { {
int A=2; int A=2; static int A=2;
for(;A>0;A‐‐) for(;A>0;A‐‐) for(;A>0;A‐‐)
B++; B++; B++;
} } }
} } }
printf("%d",B); printf("%d",B); printf("%d",B);
return 0; return 0; return 0;
} } }

30 6 2 67
Summary on Variable Scope, Life‐Time & Initialization
SCOPE : Local  (internally declared)
Global (externally declared)
LIFE TIME : auto  (temporary storage)
static (permanent storage)

1. Local Variables :
SCOPE   ‐ limited to block
LIFE TIME – temporary (auto created & destroyed)
INITIALIZATION  ‐ None

2. Global  Variables :
SCOPE   ‐ from declaration to  end of file
LIFE TIME – permanent (i.e.  static)
INITIALIZATION  ‐ Yes (to default values)

3. Static  Variables (Local yet permanant) :
SCOPE   ‐ limited to block (i.e. local)
LIFE TIME – permanent (i.e.  static)
INITIALIZATION  ‐ Yes (to default values)
68

You might also like