Introduction To Programming

Why programs ? Programming is nothing but making the computers think the same way a human thinks. Programs are made for obtaining a specific solution which can even be solved by humans which when solved by us may consume time..

Saturday, October 31, 2009

Function call by value and address:

Hi Friends Today I create a program which use method of calling function with value and address .

#include < stdio.h >
void sim(char a,char *s); //Function Declaration
void main()
{
int i=66,j=98;
sim(i,&j); //Function call
printf("\n%c %c",i,j);
}
void sim(char a,char *s) //Function Definition
{
a++;
(*s)++;
printf("%c %c",a,*s);
}



First of all I’ll explain about calling a function with value and address.

Function:
Function is set of statements grouped into a single block to do certain operation. It can be called any where in the program. There’re 3 steps to create function.

1. Function declaration (specify that we’re going to use that function)
2. Function definition (define the operation of that function)
3. Function calling(using the function in program).
While calling we give arguments(datas) to specified function as per the function definition. There’re two types of calling function depend upon the accessing the datas.

1. Call by value
2. Call by address.

Call by value:
In this type of calling we send only datas of the variable.
Eg:
function(a);

Call by address:
In this type of calling we send address of variable using &(address of).
Eg:
function(&a);

Pointer:
Only variable that can store the address of the another variable is pointer. Indirectly operate the original variable.

ok now let’s see our program.
at first I create a function with two character arguments. One of them i.e., s is pointer
in main i=66 , j=98
consider that j address is -12.

sim(i,&j);
this will pass the data of i to a i.e., a=’B’ (‘B’ ASCII is 66)
and address of j to s i.e., s=-12(because i consider that j=-12).

*s will access the data at the address(* is indirection operator). i.e., *s=j.
Now I done increment operation.
a++ after this a=’C’
(*s)++ after this j=99, *s=j.
Here you may ask one question !
If we increment *s ,how it’ll increment the j ?
I already that *s will indirectly access the j only.

so now printf will print ‘C’,’c’.
now function is over so it’ll come back to the line in main where it’s called.
Here i=66(there’s no changes). j=99.

Now It’ll print the ‘B’,’c’ (because ‘B’ ASCII is 66, ‘c’ ASCII is 99).

if you have any doubt ask me