What is difference between pass by value and pass by pointer?

Answer:
In c we can pass the parameters in a function in two different ways.
(a)Pass by value: In this approach we pass copy of actual variables in function as a parameter. Hence any modification on parameters inside the function will no reflect in the actual variable.



 For example:
#include<stdio.h>
void main(){
    int a=5,b=10;
    swap(a,b);
    printf("%d      %d",a,b);
}
void swap(int a,int b){
    int temp;
    temp =a;
    a=b;
    b=temp;
}
Output: 5    10
(b)Pass by reference: In this approach we pass memory address actual variables in function as a parameter. Hence any modification on parameters inside the function will reflect in the actual variable. For example:
#include<stdio.h>
void main(){
    int a=5,b=10;
    swap(&a,&b);
    printf("%d      %d",a,b);
}
void swap(int *a,int *b){
    int  *temp;
    *temp =*a;
    *a=*b;
    *b=*temp;
}
Output: 10 5

No comments: