Vous êtes sur la page 1sur 57

FUNCTIONS

FUNCTION??
All languages have a construct to separate and package
blocks of code. C uses the "function" to package blocks
of code.
A function is self-contained block of statements
that perform a coherent task of some kind.
Why Use Functions?
Writing functions avoids rewriting the same code
over and over.
By using functions it becomes easier to write
programs and keep track of what they are
doing(separate the code into modular units).
LOOK LIKE??
A function has a name, a list of arguments which it
takes when called, and the block of code it executes
when called.
 #include<stdio.h>
void message(); /*function prototype declaration*/
void main()
{
message(); /*function call*/
printf(“\n Friends……”);
}
void message() /* function definition */
{
printf(“\n Hi……….”);
}

 It is necessary to mention the prototype of every function that


we intend to define in the program.
 A function can be called from another function, ‘but a function
cannot be defined in another function’.
Communication??
Between calling and called functions
Mechanism used to convey information to the function
is the ‘argument’(parameter).
Parameter:
 External value used for processing is called a parameter.
 Parameters are of two types:

i. Actual parameters
ii. Formal parameters
 Parameters can passed in two ways:

i. Pass by value
ii. Pass by reference
Types of parameters…
 Actual parameters: The expression passed to a function by its caller
is called the "actual parameters”
 Formal parameters: The parameter storage local to the
function is called the "formal parameter"
Calling Convention…
Indicates two things:
i. The order in which the arguments are passed to the function
ii. Which function(calling or called)performs the cleanup of
variables when the control returns from the function
 When a function call is encountered and the arguments
are to be passed to a function two possibilities exist:
i. Arguments can be passed from left to right
ii. Arguments can be passed from right to left
• Most common calling convention is “standard calling
convention”
Additional features…
a) Return type of function
b) Calling functions by value or by reference
c) Recursion
Note:
Always ‘C’ uses positional correspondence in functions
while passing parameters
Example:
 void f(int a, int b, int c)
{
printf(%d %d %d”,a,b,c);
} z=x+y 7
main() y=z+5 12
{ x+y 15
int x=3,y=4,z=5;
f(x+y,y=z+5,z=x+y);
}
Pass by Value…
We pass ‘values’ of variables to the ‘called’ function
C passes parameters "by value" which means that the actual parameter values
are copied into local storage.
The caller and callee functions do not share any memory(-- they each have
their own copy)
Examples:
 sum=area(a,b);
 f=fact(a);

Practice: Consider the following C function


int a=3;
void f(int a)
{
void g();
a=a+2;
printf(“%d”,a);
g();
}
void g()
{
a=a+2;
printf(“%d”,a);
}
main()
{
f(a);
printf(“%d”,a);
}

Ans:5 5 5
NOTE…
“Pass by Value” is more secure than “Pass by Reference” because actual data is not
affected and a copy of it is maintained.
Ex: void f(int i)
{
i=i+1;
}
main()
{
int i=5;
f(i);
printf(“%d”,i);
}
Output: 5
Explanation: Here value of i passed as pass by value. So value of i local to main is not
changed.
Disadvantage!!!
This scheme is fine for many purposes, but it has two
disadvantages:
 Because the callee has its own copy, modifications to
that memory are not communicated back to the
caller. Therefore, value parameters do not allow the
callee to communicate back to the caller.
 Sometimes it is undesirable to copy the value from
the caller to the callee because the value is large and
so copying it is expensive
Solution…….
 The alternative is to pass the arguments "by reference".
Instead of passing a copy of a value from the caller to
the callee, pass a pointer to the value.
 In this way there is only one copy of the value at any
time, and the caller and callee both access that one
value through pointers.
POINTERS
POINTERS???
 Def.: A variable which stores the address of other
variable.
 Represented by *
 Also called Indirection operator
 There are two pointers based on memory:
 Near pointer(occupies 2bytes)
 Far pointer(occupies 4bytes)
 Pointer declaration is as ,
i location name
6 value at location
100 location number(address)
Types of pointers…
Single pointer(*)
Ex: int x=5; int *ptr; ptr=&x;
Double pointer(**)
Ex: int **pptr; pptr=&ptr;
Triple pointer(***)………
N pointer(*………*)
NULL pointer: A pointer which holds null value
Ex: int *ptr=NULL;
• WILD pointer: An uninitialized pointer
Ex: int *ptr;
char *p;
float *f;
DANGLING pointer: A pointer that points to an
address that doesn’t exist.
Ex: n1 n2 n3 nodes
200 300 NULL
100 200 300
If we delete 200 ptr, then
n1 n3
200 NULL
100 300
 CONSTANT pointer:
int *const ptr=&variable;
FUNCTIONAL pointer:
int f; variable
int f(); function
int *f; pointer
int *f(); function

int (*f)(); functional pointer


SPECIALIZED pointers:
int *p;
float *fp;
char *cp;
long *lp;
GENERIC pointer: (void *)
void *vp;

NOTE::The arithmetic operations that are allowed on


pointers are +,-
Example:
void main()
{
int i=5,*j,**k;
j=&I;
k=&j;
printf(“i=%u”,&i);
printf(“i=%u”,j);
printf(“i=%u”,*k);
printf(“j=%u”,&j);
printf(“j=“%u”,k);
printf(“k=%u”,&k);
printf(“i=%d”,i);
printf(“i=%d”,*(&i));
printf(“i=%d”,**k);
}
Output:
i=1000
i=1000
i=1000
j=2000
j=2000
k=3000
i=5
i=5
i=5
Pass by Reference…
Here we pass the location number(also called
address) of the variable to a function.
Example:
 voidswap(int*,int*); //prototype
 Swap(&a,&b); //calling function
 Void swap(int *x,int *y){} //definition
 Practice:
int x;
void f(int *x);
{
void f2(int);
*x=*x*2;
f2(*x);
}
void f2(int x)
{
x=x*2;
printf(“%d”,x);
}
main()
{
x=3;
f(&x);
printf(“%d”,x);
}
Output::6 12 6
Recursion?...
A function is said to be ‘recursive’ if a statement within
the body of a function calls the same function
(OR)
Recursion is the process of defining something in
terms of itself
Recursion internally uses stack
Example:
Q::What is the value of f(5)?
int f(int n)
{
static int r=0;
if(n<=0)
return 1;
if(n>3)
{
r=n;
return(f(n-1)+2);
}
return f(n-1)+r;
}
Output:: 18
f(int n)
{ 0
return 1;
} 1
f(n)
{
r=5;
f(n)0
return f(n-1)+r; //1+5=6
} 2
f(n)1
f(n)
{
r=5;
f(n)2
return f(n-1)+r; //6+5=11
} 3 f(n)3
f(n)
{ f(n)5
r=5;
return f(n-1)+r; //11+5=16
} 5 STACK
f(n)
{
r=5;
return(f(n-2)+2); //16+2=18
}
Test ur skills!!!
 void f(int i)
{
if(i)
{
printf(“%d”,i);
f(i+1);
}
}
main()
{
f(10);
}
Output:: 10,11,12,13,…………,32767,-32767,……….-1
Explanation:: when the value of i becomes ‘0’ that is
condition is false and execution stops.
 #define<stdio.h>
#define print(x) printf(“%d”,x);
int x;
void Q(int z)
{
z+=x;
print(z);
}
void P(int *y)
{
int x=*y+2;
Q(x);
*y=x-1;
print(x);
}
main()
{
int x=5;
P(&x);
print(x);
}

Output:: 12 7 6
 #include<stdio.h>
int fun(int n, int *f_p)
{
int t, f;
if(n<=1)
{
*f_p=1;
return 1;
}
t=fun(n-1,f_p);
f=t+*f_p;
*f_p=t;
return f;
}
int main()
{
int x=15;
printf(“%d\n”,fun(5,&x));
return 0;
}

The value printed is???


Output:: 8
 main()
{
int *ptr, i;
int A[]={10,20,30,40,50};
ptr=A+4;
for(i=1;i<5;i++)
{
*ptr=*(ptr-1); //*ptr=*ptr--;
*ptr=*ptr-1; //*ptr=*ptr-1;
}
for(i=0;i<5;i++)
{
printf(“%d”,A[i]);
}
}
Output is?????
10 20 30 40 39
Output of the following C program is………………?
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}

NOTE:ASCII value of \n(10),\0(0)


Output:: 77(‘M’)
 main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf("%d----%d",*p,*q);
}
Output: some garbage value……

Explanation:p=&a[2][2][2] you declared only two 2D


arrays, but you are trying to access the third 2D(which
you are not declared) it will print garbage values.
*q=***a …starting address of ‘a’ is assigned to integer
pointer. Now q is pointing to starting address of a. If
you print *q, it will print first element of 3D array..
Output is……???

main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
}

Note::\r-linefeed…\b-backspace
 Output is……….?

main()
{
printf("%p",main);
}
Ans :Some address will be printed.
Explanation:Function names are just addresses (just like
array names are addresses). main() is also a function. So
the address of function main will be printed. %p in printf
specifies that the argument is an address. They are
printed as hexadecimal numbers..
main()
{
static char names[5][20]={"pascal","ada","cobol","fortran","perl"};
int i;
char *t;
t=names[3];
names[3]=names[4];
names[4]=t;
for (i=0;i<=4;i++)
printf("%s",names[i]);
}
Ans ::Compiler error: Lvalue required in function main
Explanation::Array names are pointer constants. So it cannot be modified..
 Output for the following program is??????

main()
{
int i=-1;
+i;
printf("i = %d, +i = %d \n",i,+i);
}
Ans : i = -1, +i = -1
Explanation:Unary + is the only dummy operator in C.
Where-ever it comes you can just ignore it just because
it has no effect in the expressions (hence the name
dummy operator)..
 main()
{
char name[10],s[12];
scanf(“ \"%[^\"]\"",s);
}
How scanf will execute?
Ans :First it checks for the leading white space and
discards it. Then it matches with a quotation mark and
then it reads all character upto another quotation
mark..
Output of the following program is………?

void main()
{
    char *ptr="*******";
    int i;
    clrscr();
    for(i=0;i<8;i++)
{
       printf("%*.*s\n",8,i,ptr);
    }
    getch();
}
 #include<stdio.h>
#include<conio.h>
void main(){
char *ptr="*********";
int i,j;
clrscr();
for(i=0;i<11;i++){
if(i<5)
printf("%*.*s\n",5+i,2*i+1,ptr);
else
{
if(i==7)
{
*(ptr+3)=' ';
*(ptr+4)=' ';
*(ptr+5)=' ';
}
printf("%*.*s\n",9,9,ptr);
}
}

getch();
Explanation:
Meaning of %*.*s in the printf function:
-First * indicates the width i.e. how many spaces will
take to print the string.
-Second * indicates how many characters will print of
any string.
#include<stdio.h>
#include<conio.h>
int fun(int);
int i;
void main( )
{
int j;
for(;;)
{
if(j=fun(i))
printf("%d",j);
else
break;
}
}
int fun(x)
{
static int v=2;
v--;
return (v-x);
}
Output:: 1
 void main()
{
static char *s[3]={"math","phy","che"};
typedef char *( *ppp)[3];
static ppp p1=&s,p2=&s,p3=&s;
char * (*(*array[3]))[3]={&p1,&p2,&p3};
char * (*(*(*ptr)[3]))[3]=&array;
p2+=1;
p3+=2;
printf("%s",(***ptr[0])[2]);
}
Output is……….???
Ans: che
Explanation: Here

ptr: is pointer to array of pointer to string.

P1, p2, p3: are pointers to array of string.

array[3]: is array which contain pointer to array of string.

As we know p[i]=*(p+i)

(***ptr[0])[2]=(*(***ptr+0))[2]=(***ptr)[2]

=(***(&array))[2] //ptr=&array

=(**array)[2] //From rule *&p=p

=(**(&p1))[2] //array=&p1

=(*p1)[2]

=(*&s)[2] //p1=&s

=s[2]=”che”
What will be output if you will compile and execute the following c code?

#include"conio.h“
int display();
int(*array[3])();
int(*(*ptr)[3])();
void main()
{
array[0]=display;
array[1]=getch;
ptr=&array;
printf("%d",(**ptr)());
(*(*ptr+1))();
}

int display()
{
int x=5;
return x++;
}
Ans: 5
Explanation:
In this example: array []: It is array of pointer to such function which parameter is void and return
type is int data type.

ptr: It is pointer to array which contents are pointer to such function which parameter is void and
return type is int type data.

(**ptr)() = (** (&array)) () //ptr=&array

= (*array) () // from rule *&p=p


=array [0] () //from rule *(p+i)=p[i]
=display () //array[0]=display

(*(*ptr+1))() =(*(*&array+1))() //ptr=&array

=*(array+1) () // from rule *&p=p


=array [1] () //from rule *(p+i)=p[i]
=getch () //array[1]=getch
Output is……..?

void main()
{
static main;
int x;
x=call(main);
clrscr();
printf("%d ",x);
getch();
}
int call(int address)
{
address++;
return address;
}
int dynamic(int,...);
void main()
{
int x,y;
x=dynamic(2,4,6,8,10,12,14);
y=dynamic(3,6,9,12);
clrscr();
printf("%d %d ",x,y);
getch();
}

int dynamic(int s,...)


{
void *ptr;
ptr=...;
(int *)ptr+=2;
s=*(int *)ptr;
return s;
}

Output is……?8 12
In C three continuous dots is known as ellipsis which
is variable number of arguments of function. In this
example ptr is generic pointer which is pointing to first
element of variable number of argument. After
incrementing it will point third element.
What will be output if you will compile and execute the following c code?

void main()
{
int i;
float a=5.2;
char *ptr;
ptr=(char *)&a;
for(i=0;i<=3;i++)
printf("%d ",*ptr++);

}
Ans: 102 102 -90 64
Explanation:
In c float data type is four byte data type while char pointer
ptr can point one byte of memory at a time. ptr pointer will point
first fourth byte then third byte then second byte then first byte.

Content of fourth byte:


Binary value=01100110
Decimal value= 64+32+4+2=102

Content of third byte:


Binary value=01100110
Decimal value=64+32+4+2=102
Content of second byte:
Binary value=10100110
Decimal value=-128+32+4+2=-90

Content of first byte:


Binary value=01000000
Decimal value=64

Note: Character pointer treats MSB bit of each byte i.e.


left most bit of above figure as sign bit.
THANK U

Vous aimerez peut-être aussi