On 22 Feb, 12:09, "ravi" <dceravigu...@g mail.comwrote:
Hi,
i am a c++ programmer,
now i want to learn programming in c also.
so can anybody explain me the difference b/w call by reference and
call by pointer (with example if possible).
It's probably more helpful to understand that C has only one calling
convention - call by value.
When a function in C is called, arguments are passed to it "by value"
- a simple approach (not strictly accurate, but workable in my
opinion) is to regard this as creating copies of the data passed, and
passing these. Changes made in the called function are not visible to
the calling function.
$ cat ravi.c
#include <stdlib.h>
#include <stdio.h>
void ravi(int a);
int main(void) {
int a = 10;
printf("in main before calling ravi - a is %d\n",a);
ravi(a);
printf("in main after calling ravi - a is %d\n",a);
return EXIT_SUCCESS;
}
void ravi(int a) {
printf("\tin ravi - a is initially %d\n",a);
a += 20;
printf("\tin ravi - a is now %d\n",a);
}
$ ./ravi
in main before calling ravi - a is 10
in ravi - a is initially 10
in ravi - a is now 30
in main after calling ravi - a is 10
If data in the calling function is to be modified by the called
function, then you must explicitly (except in one special case, which
I'll talk about in a moment) use pointers.
$ cat ravi2.c
#include <stdlib.h>
#include <stdio.h>
void ravi(int *a); /* function now takes a pointer to int */
int main(void) {
int a = 10;
printf("in main before calling ravi - a is %d\n",a);
ravi(&a); /* pass the address of a rather than its value */
printf("in main after calling ravi - a is %d\n",a);
return EXIT_SUCCESS;
}
void ravi(int *a) {
printf("\tin ravi - a is initially %d\n",*a);
*a += 20;
printf("\tin ravi - a is now %d\n",*a);
}
$ ./ravi2
in main before calling ravi - a is 10
in ravi - a is initially 10
in ravi - a is now 30
in main after calling ravi - a is 30
The exception (sort of) is when you pass an array as an argument to a
function.
In C, the arrayname's value is the address of the first element of the
array, so passing the array allows the called function direct access
to the array.