0% found this document useful (0 votes)
23 views23 pages

Function 2 1

The document discusses nested functions and scope of variables in C. It explains that a function cannot be defined within another function but can call other functions. Local variables only exist within a function while global variables have scope in the entire program. Parameters are passed by value by default, so any changes made to parameters inside a function do not affect the original arguments.

Uploaded by

satheesh7804
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)
23 views23 pages

Function 2 1

The document discusses nested functions and scope of variables in C. It explains that a function cannot be defined within another function but can call other functions. Local variables only exist within a function while global variables have scope in the entire program. Parameters are passed by value by default, so any changes made to parameters inside a function do not affect the original arguments.

Uploaded by

satheesh7804
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/ 23

Function 2

Prof. Pranay Kumar Saha


Assistant Professor
Department of Computer Sc. and Engineering
Nested Function
A function cannot be defined within another function. It can be
called within another function.
• All function definitions must be disjoint.

Nested function calls are allowed.


• A calls B, B calls C, C calls D, etc.
• The function called last will be the first to return.

A function can also call itself, either directly or in a cycle.


• A calls B, B calls C, C calls back A.
• Called recursive call or recursion.
Example
#include <stdio.h> int ncr (int n, int r) //function def
int ncr (int n, int r); {
int fact (int n); return (fact(n) / fact(r) / fact(n-r));
void main() }
{ int fact (int n)//function def
int i, m, n, sum=0; {
scanf (“%d %d”, &m, &n); int i, temp=1;
{
for (i=1; i<=n; i++)
int i, temp=1;
for (i=1; i<=m; i+=1) temp *= i;
sum = sum + ncr(n, i) ;
printf (“Result: %d \n”, sum); return (temp);
} }
Local variables
A function can define its own local variables
The locals have meaning only within the function
• Each execution of the function uses a new set of locals
• Local variables cease to exist when the function returns
Parameters are also local
double circle_area (double d){
double radius, area;
radius = d/2.0;
area = 3.14*radius*radius;
return (area);}
Scope of variable
Part of the program from which the value of the variable can be used (seen)
• Scope of a variable - Within the block in which the variable is defined
• Block = group of statements enclosed within { }
• Local variable – scope is usually the function in which it is defined
• So, two local variables of two functions can have the same name, but they
are different variables
• Global variables – declared outside all functions (even main)
• scope is entire program by default, but can be hidden in a block if local
variable of same name defined
Local Scope replaces Global Scope
#include <stdio.h>
void myProc( )
int A; /* This A is a global variable */ {
void main( ) int A = 2; // This A is a local variable
while( A==2 )
{
{
A = 1; printf ( "A = %d\n", A );
myProc( ); break;
}
printf ( "A = %d\n", A );
printf ( "A = %d\n", A );
} }
Local Scope replaces Global Scope
#include <stdio.h>
void myProc( )
int A; /* This A is a global variable */ {
void main( ) A = 2;
while( A==2 )
{
{
A = 1; printf ( "A = %d\n", A );
myProc( ); break;
}
printf ( "A = %d\n", A );
printf ( "A = %d\n", A );
} }
Local Scope replaces Global Scope
#include <stdio.h>
void myProc(int A)
int A; /* This A is a global variable */ {
void main( ) A = 2;
while( A==2 )
{
{
A = 1; printf ( "A = %d\n", A );
myProc(A ); break;
}
printf ( "A = %d\n", A );
printf ( "A = %d\n", A );
} }
Parameter Passing: by Value and by Reference
Used when invoking functions
Call by value
• Passes the value of the argument to the function
• Execution of the function does not change the actual parameters
• All changes to a parameter done inside the function are done on a
copy of the actual parameter
• The copy is removed when the function returns to the caller
• The value of the actual parameter in the caller is not affected
• Avoids accidental changes
Parameter Passing: by Value and by Reference
Used when invoking functions

Call by Reference

• Passes the address to the original argument.

• Execution of the function may affect the original

• Not directly supported in C except for arrays


Parameter passing & return: Example 1
int main()
int change (int x)
{
{
int a=10, b;
printf (“Before x = %d\n”,x);
printf (“Initially a = %d\n”, a);
x = x / 2;
b = change (a);
printf (“After x = %d\n”, x);
printf (“a = %d, b = %d\n”, a, b);
return (x);
return 0; }
}
Parameter passing & return: Example 2
int main()
int change (int x)
{
{
int x=10, b;
printf (“Before x = %d\n”,x);
printf (“M: Initially x = %d\n”, x);
x = x / 2;
b = change (x);
printf (“After x = %d\n”, x);
printf (“M: x = %d, b = %d\n”, x, b);
return (x);
return 0; }
}
Parameter passing & return: Example 3
int main()
int change (int x)
{
{
int x=10, b;
printf (“Before x = %d\n”,x);
printf (“M: Initially x = %d\n”, x);
x = x / 2;
x = change (x);
printf (“After x = %d\n”, x);
printf (“M: x = %d, b = %d\n”, x, x);
return (x);
return 0; }
}
Parameter passing & return: Example 4
int main()
void interchange (int x, int y)
{
{
int x=10, y=5;
int temp;
printf (“M1: x = %d, y = %d\n”, x, y);
printf (“F1: x = %d, y = %d\n”, x, y);
interchange (x, y);
temp= x; x = y; y = temp;
printf (“M2: x = %d, y = %d\n”, x, y);
printf (“F2: x = %d, y = %d\n”, x, y);
return 0;
}
}
Passing Arrays to Function
Array element can be passed to functions as ordinary arguments
• IsFactor (x[i], x[0])
• sin (x[5])
An array name can be used as an argument to a function
• Permits the entire array to be passed to the function
• The way it is passed differs from that for ordinary variables
Rules:
• The array name must appear by itself as argument, without brackets or
subscripts in calling function
• The corresponding formal argument is written in the same manner
but Declared by writing the array name with a pair of empty brackets
Whole Array as Parameter
const int ASIZE = 5;
float average (int B[ ]) int main ( ) {
{ int x[ASIZE] ;
int i, total=0; float x_avg;
for (i=0; i<ASIZE; i++) x = {10, 20, 30, 40, 50};
total = total + B[i]; x_avg = average (x) ;
return ((float) total / (float)ASIZE ); return 0;
} }
Arrays used as Output Parameters
void VectorSum (int a[ ], int b[ ], int
vsum[ ], int length) int main () {
{ int x[3] = {1,2,3}, y[3] = {4,5,6},
int i; z[3];
for (i=0; i<length; i=i+1)
vsum[i] = a[i] + b[i] ; VectorSum (x, y, z, 3) ;
} PrintVector (z, 3) ;
void PrintVector (int a[ ], int length) {
return 0;
int i;
for (i=0; i<length; i++) }
printf (“%d “, a[i]);
}
The Actual Mechanism
When an array is passed to a function, the values of the array elements are not
passed to the function
• The array name is interpreted as the address of the first array element
• The formal argument therefore becomes a pointer to the first array element
• When an array element is accessed inside the function, the address is calculated using the
formula stated before
• Changes made inside the function are thus also reflected in the calling program

Passing parameters in this way is called call-by-reference


Normally parameters are passed in C using call-by-value
Library Functions
Math library functions
– perform common mathematical calculations
– #include <math.h>
– gcc prog.c -lm
Format for calling functions
FunctionName (argument);
• If multiple arguments, use comma-separated list
– printf( "%.2f", sqrt( 900.0 ) );
• Calls function sqrt, which returns the square root of its argument
• All math functions return data type double

– Arguments may be constants, variables, or expressions


Math Library function
double acos(double x) -- Compute arc cosine of x.
double asin(double x) -- Compute arc sine of x.
double atan(double x) -- Compute arc tangent of x.
double atan2(double y, double x) -- Compute arc tangent of y/x.
double ceil(double x) -- Get smallest integral value that exceeds x.
double floor(double x) -- Get largest integral value less than x.
double cos(double x) -- Compute cosine of angle in radians.
double cosh(double x) -- Compute the hyperbolic cosine of x.
double sin(double x) -- Compute sine of angle in radians.
Math Library function
double acos(double x) -- Compute arc cosine of x.
double asin(double x) -- Compute arc sine of x.
double atan(double x) -- Compute arc tangent of x.
double atan2(double y, double x) -- Compute arc tangent of y/x.
double ceil(double x) -- Get smallest integral value that exceeds x.
double floor(double x) -- Get largest integral value less than x.
double cos(double x) -- Compute cosine of angle in radians.
double cosh(double x) -- Compute the hyperbolic cosine of x.
double sin(double x) -- Compute sine of angle in radians.
String Library functions
String library functions
• perform common operations on null terminated strings
• Must include a special header file
#include <string.h>
Example
• printf ("%d", strlen(C));
• C is a null-terminated string
• Calls function strlen, which returns the number of characters in C (not
counting the ‘\0’ character)
String Library functions
strlen – returns the length of a string
strcmp – compares two strings (lexicographic)
• Returns 0 if the two strings are equal, < 0 if first string is less than
the second string, > 0 if the first string is greater than the second
string
• Commonly used for sorting strings
strcat – concatenates two strings
strcpy – copy one string to another
:Many others

You might also like