functionsce.sharif.edu/courses/98-99/1/ce153-8/resources/root/slides/lecture9_1… · • function...
TRANSCRIPT
Sharif University of TechnologyDepartment of Computer Engineering 1
Functions
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 2
Outline• Standard (Predefined) Functions
• User-Defined Functions
• Function Definition
• Flow of Execution
• …
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 3
Introduction• Until now, we learned to develop simple
algorithms– Interactions, Mathematics, Decisions, and Loops
• Real problems: very complex– Calculator
– Games, MS Word, Firefox, …
• Cannot be developed at once– Divide the problem into smaller sub-problems
– Solve the sub-problems
– Put the solutions altogether to get the final solution
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 4
Introduction• Divide and conquer
– Construct a program from smaller pieces or components
• Smaller pieces sometimes called functions
– Each piece more manageable than the original program
Divide and Conquer
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 5
Modular programming• Solving a large and complex problem
• Design the overall algorithm
• Some portions are black-box
We know it does something
But we don't worry how
Later, we think about the black-boxes and
develop them
• Black-boxes are implemented by functions
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 6
Why?• Helps manage complexity
– Smaller blocks of code
– Easier to read
• Encourages re-use of code
– Within a particular program or across differentprograms
• Provides a layer of ‘abstraction’
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 7
Building Programs from Existing Programs
• Programmers seldom start off with an empty program.
• Reasons:
– Most basic or frequently used functions have been written by other programmers.
– If you write every function by yourself, the source code may be messy and hard to maintained.
– Less code, less bugs.
– Many existing libraries have tune the performance, and thus are more reliable and robust.
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 8
Functions - Mathematical View
32)( 2
xxxf
11 is )2(
113443)2(2)2()2( 2
f
f
f(2)? isWhat
)(xf2 11
X FunctionReturned
value
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 9
Function Input and Output
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 10
Functions• Every C program starts with main() function
• Functions could be
– Pre-defined library functions
• e.g., printf, sin, tan
– Programmer-defined functions
• e.g., my_printf, area
int main(){
…}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 11
Pre-defined library functions • <math.h>
– Defines common mathematical functions– e.g. sin, cos. sqrt, pow
• <stdio.h>– Defines core input and output functions– e.g. printf, scanf
• <time.h>– Defines date and time handling functions– e.g. time, clock
• <stdlib.h>– Defines pseudo-random numbers generation functions– e.g. rand, srand
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 12
C mathematical functions• double fmod( double x, double y );
– Computes the remainder of the division operation x/y
• double exp( double arg );
– Computes the e (Euler's number, 2.7182818) raised to the given power arg
• double log( double arg );
– Computes the natural (base e) logarithm of arg
• double log10( double arg );
– Computes the common (base 10) logarithm of arg
• double sqrt( double arg );
– Computes square root of arg
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 13
C mathematical functions• double pow( double base, double exp);
– Computes the value of base raised to the power exp
• double sin( double arg );– Computes sine of arg (representing angle in radians)
• double cos( double arg );• Computes cosine of arg (representing angle in radians)
• double tan( double arg );– Computes tangent of arg (representing angle in radians)
• ...
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 14
An example#include <stdio.h>
#include <math.h>
int main(void)
{
double angle;
printf("Input angle in radians: \n");
scanf("%lf", &angle);
printf("The sine of the angle is %f\n", sin(angle) );
return 0;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 15
An example#include <stdio.h>#include <math.h>
int main(void){
double x1,y1,x2,y2, dist;printf("Enter x1 y1 x2 y2 :");scanf("%lf %lf %lf %lf", &x1, &y1, &x2, &y2);
dist = sqrt(pow((x2-x1),2) + pow((y2-y1),2)); //
printf("Distance is %lf\n", dist);return 0;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 16
Random numbers generation functions• int rand();
– Returns a uniformly distributed pseudo-random integral valuebetween 0 and RAND_MAX (0 and RAND_MAX included)
– RAND_MAX : Expands to an integer constant expression equal to themaximum value returned by the function rand(). This value isimplementation dependent.
• #define RAND_MAX 32767 /*implementation defined*/
– srand() should be called before any calls to rand() to initialize therandom number generator
• void srand( unsigned seed );– Initializes the built-in random number generator used to generate
values for rand() with the seed value seed
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 17
An Example#include <stdio.h>#include <stdlib.h>
int main(void){
unsigned int seed; /* Declare variables. */int k;/* Get seed value from the user. */printf("Enter a positive integer seed value: \n");scanf("%u",&seed);srand(seed);
/* Generate and print ten random numbers. */printf("Random Numbers: \n");for (k=1; k<=10; k++)
printf("%i ", rand());printf("\n");
return 0; /* Exit program. */}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 18
An Example#include <stdio.h>#include <stdlib.h>#include <time.h>
int main(void){
srand(time(0)); //use current time as seed for random generator /* Generate and print ten random numbers. */printf("Random Numbers: \n");for (k=1; k<=10; k++)
printf("%i ", rand());printf("\n");
return 0; /* Exit program. */}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 19 19
Random Numbers in [a b]• Generate a random number [0 .. 7]
– x = rand() % 8;
• Generate a random number [10 ..17]
– x = 10 + rand() % 8;
• rand() % (b-a+1) + a;
2000 Prentice Hall, Inc.All rights reserved.
OutlineOutline
1. Initialize seed
2. Input value for seed
2.1 Use srand to
change random
sequence
2.2 Define Loop
3. Generate and
output random
numbers
1 /* Fig. 5.9: fig05_09.c
2 Randomizing die-rolling program */
3 #include <stdlib.h>
4 #include <stdio.h>
5
6 int main()
7 {
8 int i;
9 unsigned seed;
10
11 printf( "Enter seed: " );
12 scanf( "%u", &seed );
13 srand( seed );
14
15 for ( i = 1; i <= 10; i++ ) {
16 printf( "%10d", 1 + ( rand() % 6 ) );
17
18 if ( i % 5 == 0 )
19 printf( "\n" );
20 }
21
22 return 0;
23 } Enter seed: 867
2 4 6 1 6
1 1 3 6 2
Enter seed: 67
6 1 4 6 2
1 6 1 6 4
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 21
Time Example/*This is a simple program that illustrates that calling the time function at distinct
moments and noting the different times is a simple method of timing fragments of code:*/
#include <stdio.h>
#include <sys/types.h>
#include <time.h>
int main(){
int i;
time_t t1,t2;
time(&t1);
for (i=1;i<=300;++i)
printf("%d %d %d\n",i, i*i, i*i*i);
time(&t2);
printf("\n Time to do 300 squares and cubes= %d seconds\n", (int) t2-t1);
return 0;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 22
Functions in C• Queries: Return a value
sin(), fabs()
• Commands: do some tasks, do not return any
value or we don’t use the value
printf(...)
scanf(...)
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 23
User- defined
OR
Programmer-defined function
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 24 24
Functions in CThree steps to use functions in C
Function prototype (declaration)
Introduce the function to compiler
Function definition
What the function does
Function call
Use the function
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 25
Functions - Definition Structure• Function 'header'
– Return data type (if any)
– Name• Descriptive
– Arguments (or parameter list)• Notice: data type and name
• Statements– Variable declaration– Operations– Return value (if any)
type function_name (type arg1, type arg2 ){
statements;}
double product(double x, double y)
{
double result;
result = x * y;
return result;
}
A function that calculates the product of two numbers
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 26
Function Definitions• Function definition format
return-value-type function-name( parameter-list ){
declarations and statements}
– Function-name: any valid identifier
– Return-value-type: data type of the result• void – indicates that the function returns nothing
– Parameter-list: comma separated list, declares parameters
• A type must be listed explicitly for each parameter
• No input: empty parameter list ()or void
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 27
Function Definitions• Function definition format (continued)
return-value-type function-name( parameter-list ){
declarations and statements}
– Declarations and statements: function body (block)
• Variables can be declared inside blocks
• Functions can not be defined inside other functions
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 28
Producing output
Query functions
Produce output
To produce an output
Declare output type
Generate the output by return
Function definition format (continued)return-value-type function-name( parameter-list ){
declarations and statements}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 29
The return command• To generate a result by a function
– return <value>;
– return <expression>;
• Only one value can be returned
• If noting returned
• return;
• Or until reaches right brace
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 30
The return command• return finishes running the function
• Function can have multiple return– Only one of them runs each time
• The type of the returned value = the result type– Otherwise, cast
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 31
Functions that do not return a value
• Use the return type of void
– void functionName( DataType arg_1,…)
– void functionName()
– void functionName( void)
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 32
Function – An Example
• Write a function named 'sum'– sums two integers
– returns the sum
Steps1. Function header
• return data type• function name• argument list with data types
2. Statements in function definition• variable declaration• operations• return value
int sum_int(int x, int y)
{
int result;
result = x + y;
return result;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 33
Function callCommand function
<function name> (inputs);
Query function
<variable> = <function name>(inputs);
Inputs should match by function definition
Functions are called by another function
Function call comes inside in a function
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 34
Examplevoid my_info(void){
printf("My name is Ahmad Ahmadi\n");
printf("My student number: 95222222\n");
}
int main(void){
my_info();
printf("--------------\n");
my_info();
return 0;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 35
Function Call – An Example• If the function returns a value, then the returned value need to be
assigned to a variable so that it can be stored
int GetUserInput (void); /* function prototype*/int main(void) {
int input;input = GetUserInput( );return(0); /* return 0; */
}• However, it is perfectly okay (syntax wise) to just call the function without
assigning it to any variable if we want to ignore the returned value
• We can also call a function inside another functionprintf("User input is: %d", GetUserInput( ));
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 36
Using Functions• Let int f(double x, int a) be (the beginning
of) a declaration of a function.
• Then f(expr1, expr2) can be used,
N = f(pi*pow(r,2), b+c) + d;
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 37
• Let int f(double x, int a) be (the beginning
of) a declaration of a function.
• Then f(expr1, expr2) can be used ,
N = f(pi*pow(r,2), b+c) + d;
Using Functions (continued)This is a parameter
This is an argumentThis is also an
argument
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 38
Definitions• Parameter:– a declaration of an identifier
within the '()' of a function declaration• Used within the body of the function as a variable of
that function
• Argument:– an expression passed when a function is called; becomes the initial value of the corresponding parameter
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 39
• Let int f(double x, int a) be (the beginning
of) a declaration of a function.
• Then f(expr1, expr2) can be used,
N = f(pi*pow(r,2), b+c) + d;
Using Functions (continued)
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 40
• Let int f(double x, int a) be (the beginning
of) a declaration of a function.
• Then f(expr1, expr2) can be used,
N = f(pi*pow(r,2), b+c) + d;
Using Functions (continued)
Function f is executed and
returns a value of type intResult of f is added to dSum is assigned to N
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 41
Formal and Actual Parameters• Formal parameter
– Variables declared in the formal list of the function header (written in function prototype &function definition)
• Actual parameter– Constants, variables, or expression in a function call that correspond to its formal parameter
• The number of actual parameters in a function call must be the same as thenumber of formal parameters in the function definition
• A one-to-one correspondence must occur among the actual and formalparameters. The first actual parameter must correspond to the first formalparameter and the second to the second formal parameter, an so on
• The type of each actual parameter must be the same as that of the correspondingformal parameter
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 42
An Example• If the function requires some arguments to be passed along, then the
arguments need to be listed in the bracket ( ) according to the specifiedorder
void Calc(int …, double …, char…, int…){…}
int main(void) {
int a, b;double c;char d;…Calc(a, c, d, b);
return (0);}
Function Call
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 43
Function Call – An Example#include <stdio.h>
//function prototype//global variable declaration
int main(void){
local variable declaration;statements;fn1( );fn2( );
return (0);}
void fn1(void){
local variable declaration;statements;
}
void fn2(void){
local variable declaration;statements;return;
}
1
2
3
4
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 44
Function prototype<output type> <functionname>(<input parameter
types>);
<output type> Queries: int, float,…
Command: void
<function name> is an identifier
<input parameter list> <type>, <type>, …
int, float, …
Void
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 45
Function declaration is optional if program is developed in a single filevoid my_info(void){
printf("My name is Ahmad Ahmadi\n");
printf("My student number: 95222222\n");
}
int main(void){
my_info();
printf("--------------\n");
my_info();
return 0;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 46
Example
/* Function declaration */
void my_info(void);
int main(void){
printf("This is my info");
my_info(); /* Function call */
printf("=============");
return 0;
}
/* Function definition */
void my_info(void){
printf("Student name is Ali Hosseini\n");
printf("Student number: 9522222\n");
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 47
An Example#include <stdio.h>int calSum(int,int); /*function prototype*/
int main(void){
…..…..sum = calSum(num1,num2); /* function call */…..
}
int calSum(int val1, int val2) /*function header*/{
………………
}
Formal Parameters
Formal Parameters
Actual Parameters
Introduction to Functions CS-2301, B-Term 200948
Purposes of Function Prototype
• So compiler knows how to compile calls to that function, i.e.,– number and types of arguments– type of result
• As part of a “contract” between developer and programmer who uses the function
• As part of hiding details of how it works and exposing what it does.
• A function serves as a “black box.”
• Prototype only needed if function definition comes after use in program
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 49
An ExampleFunction prototype
– Like a variable declaration• Tells compiler that the function will be defined later• Note semicolon!!
Function definition– See previous slide– Note, NO semicolon
Function return– return statement terminates execution of the
current function– Control returns to the calling function– if return expression;
• then value of expression is returned as the value of the function call
• Only one value can be returned this way
Function call– main() is the 'calling function'– product() is the 'called function'– Control transferred to the function code– Code in function definition is executed
#include <stdio.h>
/* function prototype */
double product(double x, double y);
int main()
{
double var1 = 3.0, var2 = 5.0;
double ans;
ans = product(var1, var2);
printf("var1 = %.2f\n"
"var2 = %.2f\n",var1,var2);
printf("var1*var2 = %g\n", ans);
return 0;
}
/* function definition */
double product(double x, double y)
{
double result;
result = x * y;
return result;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 50
Flow of Control• First statement executed in any program is the
first statement in the function main( )
• When another function called– logical control passed to first statement in that
function’s body
– program proceeds through sequence of statements within the function
• When last statement of function executed– control returns to where function was called
– control given to next command after the call
2000 Prentice Hall, Inc.All rights reserved.
OutlineOutline
1. Function prototype
(3 parameters)
2. Input values
2.1 Call function
3. Function definition
Program Output
1 /* Fig. 5.4: fig05_04.c
2 Finding the maximum of three integers */
3 #include <stdio.h>
4
5 int maximum( int, int, int ); /* function prototype */
6
7 int main()
8 {
9 int a, b, c;
10
11 printf( "Enter three integers: " );
12 scanf( "%d%d%d", &a, &b, &c );
13 printf( "Maximum is: %d\n", maximum( a, b, c ) );
14
15 return 0;
16 }
17
18 /* Function maximum definition */
19 int maximum( int x, int y, int z )
20 {
21 int max = x;
22
23 if ( y > max )
24 max = y;
25
26 if ( z > max )
27 max = z;
28
29 return max;
30 }
Enter three integers: 22 85 17
Maximum is: 85
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 52
Receive nothing and return nothing#include <stdio.h>
void greeting(void); /* function prototype */
int main(void)
{
greeting( );
greeting( );
return(0);
}
void greeting(void)
{
printf("Have fun!! \n");
}
Have fun!!
Have fun!!
Press any key to continue
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 53
Receive nothing and return int#include <stdio.h>
int getInput(void) /* ignore function prototype */
{
int number;
printf("Enter a number:");
scanf("%d",&number);
return number;
}
int main(void)
{
int num1, num2, sum;
num1 = getInput( );
num2 = getInput( );
sum = num1 + num2;
printf("Sum is %d\n",sum);
return(0);
}
Enter a number: 5
Enter a number: 4
Sum is 9
Press any key to continue
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 54
Receive parameter(s) and return nothing#include <stdio.h>
int getInput(void);
void displayOutput(int);
int main(void)
{
int num1, num2, sum;
num1 = getInput();
num2 = getInput();
sum = num1 + num2;
displayOutput(sum);
return(0);
}int getInput(void){
int number;printf("Enter a number:");scanf("%d",&number);return number;
}void displayOutput(int sum){
printf("Sum is %d \n",sum);}
Enter a number: 5
Enter a number: 4
Sum is 9
Press any key to continue
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 55
Exmaple: my_fabs (Version 1)double my_fabs(double x){
double res;
if(x >= 0)
res = x;
else
res
return
= -1 * x;
res;
}
* b));
void main(void){
double d = -10;
double b;
b = my_fabs(d);
printf("%f\n", b);
printf("%f\n", my_fabs(-2
}
10
20
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 56
Exmaple: my_fabs (Version 2)double my_fabs(double x){
if(x >= 0)
return x;
return (-1 * x);
}
void main(void){
double d = -10;
double b;
b = my_fabs(d);
printf("b = %f\n", b);
b = my_fabs(-2 * d);
printf("b = %f\n", b);
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 57
Output of functionsA function can produce at most one output
Output of functions can be dropped
drop the output of sinsin(f); //we
Casting in functionsCast for input Prototype: void f(int a, double b);
Call: f(10.1, 20.2);
Cast for outputf(int a);
= f(10);
Prototype: int
Call: double d
Cast in return
int f(int a){
...
return 10.20
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 59
Scope of VariablesUntil now, Variables
Are declared in the start of functions
Are used any where in the function after declaration
Can we used them outside of function?
Can we used them in other functions?
Scope of variable
A range of code that the variable can be used
Variable cannot not be used outside of itsscope
Compile error
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 60
Scopes vs. BlocksScopes are determined by Blocks
Start with { and finished by }
Example: statements of a function, statement of aif or while, …
Variables
Can be declared in a block
Can be used in the declared block
Cannot be used outside the declared block
The Declared block is the scope of the variable
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 61
Variables in Blocks
61
", i);
#include <stdio.h>
int main(void){
int i;
for(i = 1; i <= 10; i++){
int number;
printf("Enter %d-th number:
scanf("%d", &number);
if((number % 2) == 0)
printf("Your number is even\n");
else
printf("Your number is odd\n");
}
/* compile error
printf("The last number is %d\n", number); */
return 0;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 62
Nested Scopes/BlocksScopes can be nested
Example: Nested if, nested for, …
int main(){ //block 1
int i;
{ //block 2
int j;
{ //block 3
int k;
}
int m;
}
return 0;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 63
Variables in Nested BlocksAll variables from outer block can be used
inner blocks
Scope of outer block contains the inner block
Variables in inner block cannot be used in
outer block
Scope of the inner block does not contains the
outer block
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 64
Variables in Nested Blocks: Exampleint k;
for(int i = 0; i < 10; i++){
/* block 1 */
if(i > 5){
/* block 2 */
int j = i;
...
j; compile error */
}
while(k > 10){
/* block 3 */
int l = i;
/* int m =
...
}
/* k = l; compile error */
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 65
Same Variables in Nested Block If a variable in inner block has the same identifier of a
variable in outer block
The inner variable hides the outer variable
Changing inner variables does not change outer variable
int i=10 ,j = 20;
printf("outer i =%d, %d\n",i,j);if(true){
int i=100;
j = 25;
printf("outer i =%d, %d\n",i,j);
}
printf("outer i =%d, %d\n",i,j);
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 66
Local VariablesAll defined variables in a function are the local
variable of the function
Can ONLY be used in the function, not other functions
void func(void){
int i, j;
float f;
/* These are local variables */
error,
error,
why? */
why? */
}
int main(void){
i = 10; /* compile
f = 0; /* compile
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 67
Global VariablesGlobal variables are defined outside of all functions
Global variables are initialized to zero
Global variables are available to all subsequent
functions
void f(){
i = 0; // compile error
}
int i;
void g(){
int j = i; // g can use i
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 68
Global Variables: Example
\n", i);
\n", f);
int i, j;
float f;
void func(void){
printf("i = %d
printf("f = %f
i = 20;
}
void f(){
printf("%d", i);
}
int main(void){
f = 1000;
func();
f();
return 0;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 69
Exmaple: my_fabs (Version 1)double my_fabs(double x){
double res;
if(x >= 0)
res = x;
else
res
return
= -1 * x;
res;
}
* b));
void main(void){
double d = -10;
double b;
b = my_fabs(d);
printf("%f\n", b);
printf("%f\n", my_fabs(-2
}
10
20
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 70
Exmaple: my_fabs (Version 2)double my_fabs(double x){
if(x >= 0)
return x;
return (-1 * x);
}
void main(void){
double d = -10;
double b;
b = my_fabs(d);
printf("b = %f\n", b);
b = my_fabs(-2 * d);
printf("b = %f\n", b);
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 71
Parameter Passing by Global Variables: my_fabs (V.3)
double x;
void my_fabs(void){
x = (x > 0) ? x : -1 * x;
}
void main(void){
= -10;double b, d
x = d;
my_fabs();
b = x;
printf("b = %f\n", b);
}
Don’t use this method.
Parameters should be passed
by input parameter list.
Global variable are used to
define (large) variables that
are used in many functions
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 72
Prototype Example#include <stdio.h>
int max(int x,int y);
int main(void)
{
int a = 10, b = 20;
int m = max(a, b);
printf("m is %d", m);
return 0;
}
int max(int x, int y)
{
if (x > y)
return x;
else
return y;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 73
Prototype Example#include <stdio.h>
int max(int,int);
int main(void)
{
int a = 10, b = 20;
int m = max(a, b);
printf("m is %d", m);
return 0;
}
int max(int x, int y)
{
if (x > y)
return x;
else
return y;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 74
Prototype Example#include <stdio.h>
int max(int a,int b);
int main(void)
{
int a = 10, b = 20;
int m = max(a, b);
printf("m is %d", m);
return 0;
}
int max(int x, int y)
{
if (x > y)
return x;
else
return y;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 75
How Function Call Works Function call is implemented by “stack”
Stack is a part of main memory
When a function calls
Its variables including the inputs are allocated in stack
The value of input parameters from caller function is pushed to stack of called function
When function finished, its stack is freed
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 76
Example: print_sub function#include <stdio.h>
void print_sub(double a, double b){
double res;
res = a - b;
printf("Sub of %f and %f is %f\n", a, b, res);
}
int main(void){
double d1 = 10, d2 = 20;
print_sub(56.0,6.0); //What is the output?
print_sub(d1,d2); //output?
print_sub(d1,d2 + d2); //output?
return 0;
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 77
print_sub: What happen?
double a = 56.0;
double b = 6.0;
double res;
res = a - b;
print_sub(56.0, 6.0);
56.0 is copied the memory location a
6.0 is copied to memory location b
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 78
print_sub: What happen?print_sub(d1, d2);
Value of d1 is copied the memory location a
Value of d2 is copied to memory location b
double a = 10;
double b = 20;
double res;
res = a - b;
Call by Value
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 79
Call by valueIn call by value mechanism
The values are copied to the function
Only the copy of variable’s value (copy of actual parameter’s value) is passed to the function.
If we change values in the function
The copied version is changed
The original value does not affected
Any modification to the passed value inside the function will not affect the actual value
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 80
Call by value – An Example• How are the arguments passed
into functions?– 'Pass by value'– function arguments are
expressions
– In the function call:
• Expressions are evaluated and copies of their values are put into temporary memory locations
• The names of the corresponding parameters in the function definition are made to be the names of the copies
– The values of the expressions in the function call are notchanged
#include <stdio.h>
double product(double x, double y);
int main()
{
int a = 10;
double var1 = 3.0, var2 = 5.0;
double ans;
ans = product(var1, var2);
printf("var1 = %.2f\n"
"var2 = %.2f\n",var1,var2);
printf("var1*var2 = %g\n", ans);
}
/* function definition */
double product(double A, double B)
{
double result;
result = A * B;
return result;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 81
Call by value – An Example#include <stdio.h>int calSum(int,int); /*function protototype*/
int main(void){
int sum, num1, num2;
printf("Enter two numbers to calculate its sum:\n");scanf("%d%d",&num1,&num2);
sum = calSum(num1,num2); /* function call */printf("\n %d + %d = %d", num1, num2, sum);return(0);
}
int calSum(int val1, int val2) /*function definition*/{
int sum; sum = val1 + val2; val2 = 100;return sum;
}
Enter two numbers to calculate its sum:
4
9
4 + 9 = 13
Press any key to continue
?num2
?num1
?sum
4num2
9num1
?sum
4val2
9val1
?sum
4val2
9val1
13sum
100val2
9val1
13sum
4num2
9num1
13sum
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 82
Example: print_sub function#include <stdio.h>
void print_sub(double a, double b){
double res;
res = a - b;
printf("Sub of %f and %f is %f\n", a, b, res);
}
int main(void){
double d1 = 10, d2 = 20;
print_sub(56.0,6.0); //What is the output?
print_sub(d1,d2); //output?
print_sub(d1,d2 + d2); //output?
return 0;
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 83
add function (wrong version)res){void add(double a, double b, double
res = a + b;
return;
}
int main(void){
10.1, d2 = 20.2;double d1 =
double result = 0;
add(56.0, 6.7,
printf("result
result);
= %f\n", result);
add(d1, d2, result);
printf("result = %f\n", result);
}
result = 0
result = 0
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 84
Call by reference• Call by reference
– In this method, the reference (memory address)of the variable is passed to the function. Anymodification passed done to the variable insidethe function will affect the actual value
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 85
Call by reference#include <stdio.h>
void CalByVal(a, b)
{
a = 0; b = 10;
}
void CalByRef(int *a, int *b) // CalByRef(int *p, int *q)
{
*a = 0; *b = -5;
}
int main(void)
{
int a = 1, b = 5;
printf("Before cal CalByVal: a = %d, b = %d\n", a, b);
CalByVal(a, b);
printf("After cal CalByVal: a = %d, b = %d\n", a, b);
printf("Before cal CalByRef: a = %d, b = %d\n", a, b);
CalByRef(&a, &b);
printf("After cal CalByRef: a = %d, b = %d\n", a, b);
return 0; /* Exit program. */
}
main5b
1a
CalByVal5b
1a
CalByVal10b
0aCalByRefb
a
main-5b
0a
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 86
Call by reference
• Instead of product()– prod_sum()
– How can I get the function to give both product and sum?
• put * in front of variable name in prototype and function definition
• put & in front of variable names in function call
#include <stdio.h>
void prod_sum(double x, double y,
double *ptr1, double *ptr2);
int main()
{
double var1 = 3.0, var2 = 5.0;
double prod, sum;
prod_sum(var1, var2, &prod, &sum);
printf("var1= %g\n"
"var2= %g\n",var1, var2);
printf("prod= %g\n" "sum= %g\n", prod, sum);
}
/* function definition */
void prod_sum(double A, double B,
double *rslt_prod, double *rslt_sum)
{
*rslt_prod = A * B;
*rslt_sum = A + B;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 87
Recursion• Recursion is a technique that solves a problem by solving a smaller
problem of the same type
• A recursive function is a function invoking itself, either directly orindirectly
– Recursion: A → B → C → D → A
• Concept of recursive function (generally):
– A recursive function is called to solve a problem
– The function only knows how to solve the simplest case of the problem. Whenthe simplest case is given as an input, the function will immediately returnwith an answer if (stopping case)
solve itelse
reduce the problem using recursion
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 88
RecursionRecursiveAlgorithm
An algorithm uses itself to solve the problem
There is a basic problem with known solution
Recursive Algorithms are implemented by
recursive functions
Recursive function
A function which calls itself
There is a condition that it does not call itself
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 89
Recursion• Any problem that can be solved recursively can also be
solved iteratively (using loop)
• Recursive functions are slow and takes a lot of memoryspace compared to iterative functions
• So why bother with recursion? There are 2 reasons:– Recursion approach more naturally resembles the problem
and therefore the program is easier to understand anddebug
– Iterative solution might not be apparent
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 90
An Example: xy
• In this example, we want to calculate x to the power of y– i.e. xy
• If we analyze the formula for xy, we could see that xy
could be written as (x being multiplied to itself, y times)– An example is 24, which can be written as
24 = 2 x 2 x 2 x 2 (in this case, x = 2, y = 4)
– 24 could also be rewritten as24 = 21 x 23 where 21 = 2 (i.e the number itself)
• Therefore, we could divide the problem into two stage:
– Simplest case: when y = 1, the answer is x
– Recursive case, we need to solve for x * x(y-1)
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 91
Introduction
Factorial
n! = n x n-1 x … x 2 x 1
n! = n x (n-1) !
GCD
GCD(a, b) = EuclideanAlgorithm
GCD(a, b) = GCD(b, a mod b)
There is a simple (basic) problem which we can
solve it directly (without recursion)
Factorial: 1! = 1
GCD: b == 0
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 92
Euclid’s algorithm in Cint gcd(int m, int n){int r;while ( (r = m % n) != 0) {m = n;n = r;
}return n;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 93
Recursion solution of xy
#include <stdio.h>
double XpowerY(double, int);
int main(void)
{
double power, x; int y;
printf("Enter the value of x and y:\n");
scanf("%f%d", &x, &y);
power = XpowerY(x, y);
printf("%.2f to the power of %d is %.2f\n\n", x, y, power);
return(0);
}
double XpowerY(double x, int y)
{
if (y ==1)
return x;
else
return x * XpowerY(x, y-1);
}
Enter the value of x and y:
2
3
2.00 to the power of 3 is 8.00
Press any key to continue
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 94
#include <stdio.h>
int factorial(int n){
int res, tmp;
if(n == 1)
/* The basic problem */
res = 1;
else{
/* recursive call */
tmp = factorial(n - 1);
res = n * tmp;
}
return res;
}
fac);
void main(void){
int i = 4;
int fac = factorial(i);
printf("%d! = %d\n", i,
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 95
Factorial#include <stdio.h>double fact(double);int main(void){
double n, result;printf("Please enter the value of n:");scanf("%lf", &n);
result = fact(n);printf(" %.f! = %.2f\n", n, result);return(0);
}double fact(double n){
if (n <= 1)return 1;
elsereturn n * fact(n-1);
}
Enter the value of n: 3
3! = 6.00
Press any key to continue
int fact(int n){
int factres = 1;while(n>1){
factres = factres*n;n--;
}return (factres);
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 96 10-96
How C Maintains the Recursive Steps
• C keeps track of the values of variables by thestack data structure.
– Recall that stack is a data structure where the lastitem added is the first item processed
– There are two operations (push and pop) associatedwith stack
a
b
c
b
c
d
b
c
pop push d
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 97
How C Maintains the Recursive Steps
• Each time a function is called, the executionstate of the caller function (e.g., parameters,local variables, and memory address) arepushed onto the stack
• When the execution of the called function isfinished, the execution can be restored bypopping up the execution state from the stack
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 98
#include <stdio.h>
int factorial(int n){
int res, tmp;
if(n == 1)
/* The basic problem */
res = 1;
else{
/* recursive call */
tmp = factorial(n - 1);
res = n * tmp;
}
return res;
}
fac);
void main(void){
int i = 4;
int fac = factorial(i);
printf("%d! = %d\n", i,
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 99
Function Call Graphfactorial(4)
n = 4, tmp = ?, res = ?
factorial(3)
n = 3, tmp = ?, res = ?
factorial(2)
n = 2, tmp = ?, res = ?
factorial(1)
n = 1, res = ?
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 100
Function Call Graphfactorial(4)
n = 4, tmp = ?, res = ?
factorial(3)
n = 3, tmp = ?, res = ?
factorial(2)
n = 2, tmp = ?, res = ?
factorial(1)
n = 1, res = 1
1
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 101
factorial(4)
n = 4, tmp = ?, res = ?
factorial(3)
n = 3, tmp = ?, res = ?
factorial(2)
n = 2, tmp = 1, res = 2
factorial(1)
n = 1, res = 1
1
2
Function Call Graph
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 102
factorial(4)
n = 4, tmp = ?, res = ?
factorial(3)
n = 3, tmp = 2, res = 6
factorial(2)
n = 2, tmp = 1, res = 2
factorial(1)
n = 1, res = 1
1
2
6
Function Call Graph
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 103
factorial(4)
n = 4,tmp = 6,res = 24
factorial(3)
n = 3, tmp = 2, res = 6
factorial(2)
n = 2, tmp = 1, res = 2
factorial(1)
n = 1, res = 1
1
2
6
Function Call Graph
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 104
Recursive Steps of xy
#include <stdio.h>
double XpowerY(double, int);
int main(void)
{
double power, x; int y;
printf("Enter the value of x and y:\n");
scanf("%lf%d", &x, &y);
power = XpowerY(x, y);
printf("%.2f to the power of %d is %.2f\n\n", x, y, power);
return(0);
}
double XpowerY(double x, int y)
{
if (y ==1)
return x;
else
return x * XpowerY(x, y-1);
}
x = 2; y = 4;
x * XpowerY(2, 3)
x = 2; y = 3;
x * XpowerY(2, 2)
x = 2; y = 2;
x * XpowerY(2, 1)
x = 2; y = 1;
return x;
2*8
2
2 * 2
2 * 4
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 105
ExamplesRecursive version of GCD?
Recursive version of Fibonacci numbers
Fibonacci numbers
1, 1, 2, 3, 5, 8, ...
Print digits: left-to-right and right-to-left
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 106
#include <stdio.h>
int GCD(int a, int b){
if(b == 0)
return a;
else
return GCD(b, a % b);
}
int main(void){
printf("GCD(1, 10)
printf("GCD(10, 1)
= %d \n",
= %d \n",
GCD(1, 10));
GCD(10, 1));
printf("GCD(15, 100)
printf("GCD(201, 27)
= %d \n", GCD(15, 100));
= %d \n", GCD(201, 27));
return 0;
}
#include <stdio.h>
return 0;
}
int fibo(int n){
if(n
else
== 1)
return 1;
if(n == 2)
return 1;
else
return fibo(n - 1) + fibo(n - 2);
}
int main(void){
printf("fibo(1)
printf("fibo(3)
printf("fibo(5)
printf("fibo(8)
= %d\n",
= %d\n",
= %d\n",
= %d\n",
fibo(1));
fibo(3));
fibo(5));
fibo(8));
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 108
Fibonacciint Fib (int n){
int temp = 1; /* handles base cases */ if (n > 2)
temp = Fib(n-1) + Fib(n-2);return temp;
}
/* Iterative Version */
int fibonacci(int k)
{
int a,b,c,i;
if (k <= 1) return 1;
else
{
a = 1;
b = 1;
i = 2;
while (i <= k)
{
c = a + b;
a = b;
b = c;
i++;
}
return(c);
}
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 109
Fibonacci
int Fib (int x){
/* handles base cases of */ /* Fib(1) and Fib(2) */ int temp = 1; if (x > 2) /* other cases */
temp = Fib(x-1) + Fib(x-2);return temp;
}
x = 5; temp = 1;
temp = Fib(4) + Fib(3);return temp;
x = 1; temp = 1;
return temp;
x = 4; temp = 1;
temp = Fib(3) + Fib(2);return temp;
x = 5; temp = 1;
temp = Fib(2) + Fib(1);return temp;
x = 1; temp = 1;
return temp;x = 1; temp = 1;
return temp;
x = 5; temp = 1;
temp = Fib(2) + Fib(1);return temp;
x = 1; temp = 1;
return temp;
x = 1; temp = 1;
return temp;
x = 5; temp = 1;
temp = 1 + Fib(1);return temp;
x = 5; temp = 1;
temp = 1 + 1;return temp;
x = 4; temp = 1;
temp = 2 + Fib(2);return temp;
x = 4; temp = 1;
temp = 2 + 1;return temp;
x = 5; temp = 1;
temp = 3 + Fib(3);return temp;
x = 5; temp = 1;
temp = 1 + Fib(1);return temp;
x = 5; temp = 1;
temp = 1 + 1;return temp;
x = 5; temp = 1;
temp = 3 + 2;return temp;
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 110
Fibonacci
fib(5)
fib(4) fib(3)
fib(3) fib(2)
fib(2) fib(1)
fib(2) fib(1)
1
1
1
12 1
3 2
5int Fib (int n){
/* handles base cases of */ /* Fib(1) and Fib(2) */ int temp = 1; if (n > 2) /* other cases */
temp = Fib(n-1) + Fib(n-2);return temp;
}
76
#include <stdio.h>
return 0;
}
void print_digit_right_left(int n){
int digit = n % 10;
printf("%d ", digit);
if(n >= 10)
print_digit_right_left(n / 10);
}
int main(void){
printf("\n print_digit_right_left(123): ");
print_digit_right_left(123);
printf("\n print_digit_right_left(1000): ");
print_digit_right_left (1000);
#include <stdio.h>
return 0;
}
void print_digit_left_right(int n){
if(n >= 10)
print_digit_left_right(n / 10);
int digit = n % 10;
printf("%d ", digit);
}
int main(void){
printf("\n print_digit_left_right(123): ");
print_digit_left_right(123);
printf("\n print_digit_left_right(1000): ");
print_digit_left_right (1000);
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 113
Indirect recursionWhat we have seen are direct recursion
A function calls itself directly
Indirect recursion
A function calls itself using another function
Example:
Function A calls functionB
Function B calls functionA
#include <stdio.h>
#include <stdbool.h>
bool
bool
is_even(int n);
is_odd(int n);
bool is_even(int n){
true;
false;
if(n == 0)
return
if(n == 1)
return
else
return is_odd(n - 1);
}
bool is_odd(int n){
if(n == 0)
return false;
if(n == 1)
return true;
else
return is_even(n - 1);
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 115
int main(void){
is even\n");
if(is_even(20))
printf("20
else
printf("20 is odd\n");
is odd\n");
if(is_odd(23))
printf("23
else
printf("23 is even\n");
return 0;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 116
Bugs & Avoiding Them
Recursion must finish, be careful a bout basic
problem in the recursive functions
No base problem Stack Overflow
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 117
Exercise• What is the output of the following program
void function2()
{
printf("In function 2\n");
}
void function1()
{
function2();
printf("In function 1\n");
}
#include <stdio.h>
void function3()
{
printf("In function 3\n");
function2();
}
int main()
{
function1();
function3();
return 0;
}
In function 2In function 1In function 3In function 2
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 118
Storage Classes• Variables have attributes
– Have seen name, type, value
– Scope
• Where variable can be referenced in program
– Storage class
• How long variable exists in memory
– Linkage
• For multiple-file program, which files can use it
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 119
Organizing Multi-File Programs• A large C program should be divided into multiple files
// main.c#include <stdio.h>void Test(){
// …}int main(){
// …return 0;
}
// math.cdouble mathVar;double sin(){
double tempSin;// …
return tempSin;}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 120
Scope of Identifiers• Scope of a declaration of an identifier
– The region of the program that the declaration isactive (i.e., can access the variable, function, label,etc.)
• Five types of scope:– Program (global scope)– File– Function prototype– Function– Block ("between the { } scope")
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 121
Scope of Identifiers - Program Scope• Program (global) scope
– if declared outside of allfunctions
– "Visible" to all functions from point of declaration
– Use only when necessaryand then very carefully!!
– If there exist a local variableand a global variable withthe same name, thecompiler will refer to thelocal variable
– Visible to functions in othersource files
#include <stdio.h>
int a = 10;
double product(double x, double y);
int main()
{
double var1 = 3.0, var2 = 5.0;
double ans;
ans = product(var1, var2);
// …
}
/* function definition */
double product(double x, double y)
{
double result; a = 20;
result = x * y;
return result;
}
a = 10
a = 20
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 122
An Example// File name: main.c
#include <stdio.h>
int a = 10;
/* function definition */
double product(double x, double y)
{
double result;
// …
a = 70;
return result;
}
int main()
{
a = 80;
}
// File name: ExternFile.c
extern int a = 10;
/* function definition */
void TestExtern()
{
// …
a = 90;
// …
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 123
Scope of Identifiers - File Scope
• File scope
– Keyword static• Makes variable a ‘visible’
only within this source file
– Use file scope to avoidnaming conflict if multiplesource files are used
#include <stdio.h>
static int a = 10;
double product(double x, double y);
int main()
{
double var1 = 3.0, var2 = 5.0;
double ans;
ans = product(var1, var2);
// …
}
/* function definition */
double product(double x, double y)
{
double result;
result = x * y;
return result;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 124
An Example// File name: main.c
#include <stdio.h>
static int a = 10;
/* function definition */
double product(double x, double y)
{
double result;
// …
a = 70;
return result;
}
int main()
{
a = 80;
}
// File name: ExternFile.c
extern int a = 10;
/* function definition */
void TestExtern()
{
// …
a = 90;
// …
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 125
• Function prototype scope– Identifiers x and y are not
visible outside the prototype
– Thus, names in the prototypedo not have to match names inthe function definition
• MUST match types, however!
Scope of Identifiers - Function Prototype Scope
#include <stdio.h>
double product(double x, double y);
int main()
{
int a = 10;
double var1 = 3.0, var2 = 5.0;
double ans;
ans = product(var1, var2);
printf("var1 = %.2f\n"
"var2 = %.2f\n",var1,var2);
printf("var1*var2 = %g\n", ans);
}
/* function definition */
double product(double A, double B)
{
double result;
result = A * B;
return result;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 126
• Function scope– Active from the beginning to the end of a function
Scope of Identifiers - Function Scope
#include <stdio.h>
int main()
{
int a;
// …
return 0;
}
int FunctionScopeTest()
{
int b;
// …
return 0;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 127
Scope of Identifiers - Block Scope• Block (local) scope
– A block is a series of statements enclosed in braces { }
– The identifier scope is active from the point of declaration to the end of the block ( } )
– Nested blocks canboth declare the same variable name and not interfere
#include <stdio.h>
double product(double x, double y);
int main()
{
int a = 10;
double var1 = 3.0, var2 = 5.0;
double ans;
ans = product(var1, var2);
// …
}
/* function definition */
double product(double x, double y)
{
double result; // a = 60; Error
result = x * y;
return result;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 128
Storage ClassesStorage class(Refers to the lifetime of a variable)
How memory is allocated for the variable
Until when the variable exists
How it is initialized
Storage classes in C
Automatic
External
Static
Register
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 129
Storage Classes• Refers to the lifetime of a variable
• Local variables only exist within a function by default. When calling a function repeatedly, we might want to– Start from scratch – reinitialize 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)
How use?
storage_classes variable_type variable_name
autoregisterstaticextern
intfloatdoublechar
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 131
Storage Classes: Automatic• Automatic storage class
• Variable created when program enters its block• Variable destroyed when program leaves block• Only local variables of functions can be
automatic• Automatic by default• keyword auto explicitly declares automatic
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 132
Storage Classes: Automatic• The example above defines two variables with the
same storage class. auto can only be used within functions, i.e. local variables.
• auto is the default storage class for local variables.
{int Count;auto int Month;
}
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 133
Auto - Example#include <stdio.h>void auto_example(void);
int main(void){
int i;
printf("Auto example:\n");
auto_example( );auto_example( );auto_example( );
return(0);
}
void auto_example(void)
{
auto int num = 1;
printf(" %d\n",num);
num = num + 2;
}
Auto example:
1
1
1
Press any key to continue
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 134
Storage Classes: ExternalAll global variables are external by default
Are generated when program starts
Are destroyed when program finishes
Usage of keyword “extern”
To use global variables in other files
To emphasize that variable is global
This usage is optional
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 135
Storage Classes: StaticKeyword “static” comes before them
For local variables:
1) Generated in the first run of the block
2) Destroyed when program finishes
3) Initialized
If no value initialized by 0
Only initialized in the first run of the block
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 136
Static storage class• However the static keyword can be applied to
a local variable so that the variable still existeven though the program has gone out of thefunction. As a result, whenever the programenters the function again, the value in thestatic variable still holds
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 137
Static - Example#include <stdio.h>void auto_example(void);
int main(void){
int i;
printf("Static example:\n");static_example( );static_example( );static_example( );return(0);
}
void static_example(void)
{
static int num = 1;
printf(" %d\n",num);
num = num + 2;
}
Static example:
1
3
5
Press any key to continue
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 138
Storage Classes: Static
Keyword “static” comes before them
For global variables:
1) Generated when program starts
2) Destroyed when program finishes
3) Always initialized
If no value initialized by 0
4) Is not accessible for other files
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 139
Storage Classes: RegisterKeyword “register” comes before them
Can be used for local variables
Compiler tries to allocated the variable in
registers of CPU
But does not guaranteed
Registers are very fast and small memories
Improve performance
The register Storage Class
• The register storage class is used to define local variables that should be stored in a register instead of RAM.
• The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions.
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 141
Storage Classes, Register: Examples
register int i;
i++)for(i = 0; i < 100;
…
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 142
Storage Classes: Examplesint i;
void func(void){
int j;
printf("i = %d \n", i);
printf("j = %d \n", j);
i = 20;
}
int main(void){
func();
func();
i = 30;
func();
return 0;
}
i =???
j =???
i =???
j =???
i =???
j =???
i = 0
j = 0
i = 20
j = 0
i = 30
j = 0
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 143
Storage Classes, Static:Examplesvoid func(void){
int j;
static int i;
printf("i = %d \n", i);
printf("j = %d \n", j);
i = 20;
}
int main(void){
func();
func();
/* i = 30; compile error, why? */
func();
return 0;
}
i = ???
j = ???
i = ???
j = ???
i = ???
j = ???
i = 0
j = 0
i = 20
j = 0
i = 20
j = 0
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 144
Storage Classes, Static:Examplesvoid func(void){
int j;
static int i=10;
printf("i = %d \n", i);
printf("j = %d \n", j);
i = 20;
}
int main(void){
func();
func();
return 0;
}
i = ???
j = ???
i = ???
j = ???
i = 10
j = 0
i = 20
j = 0
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 145
Storage Classes, Extern: Examplesint i = 10, j = 20;
void print(void){
printf("i = %d, j = %d\n", i, j);
}
int main(void){
extern int i; // i refers the global i
int j; // j is new variable
print();
i = 1000;
j = 2000;
print();
return 0;
}
i = ?, j = ?
i = ?, j = ?
i = 10, j = 20
i = 1000, j = 20
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 146
Inline Functions & MacroFunction call using stack has its overhead
2 approaches to reduce the overhead
inline function
To ask from compiler to compile it as inline, but
no guarantee
int f(float x)inline
Macros
#define PRINT_INT(X) printf("%d\n", X)
Sharif University of TechnologyDepartment of Computer Engineering 147
If the same sequence of steps or instructions is required in several different places in a program, you will normally write a function for the steps and call the function whenever these steps are required. But this involves time overhead.
Also can place the actual sequence of steps wherever they are needed in the program, but this increase the program size and memory required to store the program. Also need retyping process or copying a block of program.
Use function if the sequence of steps is long. If small, use macros or inline function, to eliminate the need for retyping and time overhead.
Inline Functions
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 148
Example: GCD#define PRINT_INT(x) printf("%d\n",x)
int b){ /* return gcd of a and b */inline int gcd(int a,
int temp;
while(b != 0){
temp = a % b;
a = b;
b = temp;
}
return a;
}
void main(void){
int i = 20, j = 35, g;
g = gcd(i, j);
", i , j);printf("GCD of %d and %d =
PRINT_INT(g);
", j , i);
g = gcd(j, i);
printf("GCD of %d and %d =
PRINT_INT(g);
}
Sharif University of TechnologyDepartment of Computer Engineering 149
Need #define compiler directive. For example, to obtain just the area of a triangle, we could create a macro,
Macros
Sharif University of TechnologyDepartment of Computer Engineering 150
Example for finding an average of 4 numbers (a, b, c and
d),
#define avg(x, y) (x + y)/2.0
Then in the program we can define something like this,
avg1 = avg(avg(a, b), avg(c, d))
Doing the substitution,
avg4 = ((a + b)/2.0 + (c + d)/2.0) / 2.0
The drawback: nesting of macros may result in code that
difficult to read.
C FUNCTIONS
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 151
151
Header Files• Header files contain
– Function prototypes
– Definitions of data types and constants
• Header files ending with .h
– Programmer-defined header files#include “myheader.h”
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 152
Typical C Programming Style• A lot of small C programs, rather than a few
large ones• Each .c file contains closely related functions
• Usually a small number of functions
• Header files to tie them together
Input and Output – Lecture 4
Sharif University of TechnologyDepartment of Computer Engineering 153
Header files• In applications with multiple C programs,
function prototypes are typically provided in header files
• I.e., the ‘.h’ files that programmers include in their code
• Grouped by related functions and features• To make it easier for developers to understand
• To make it easier for team development
• To make a package that can be used by someone else