What is difference between pass by value and pass by address in C

1 Answer

0 votes
#include <stdio.h> 
 
void swap_by_value(int a, int b);
void swap_by_address(int *a, int *b);
  
int main(int argc, char **argv) 
{ 
    int a = 3, b = 7;
     
    swap_by_value(a, b); // Pass by value
    printf("a = %d b = %d\n",a, b); // not swapped
     
    swap_by_address(&a, &b); // Pass by address
    printf("a = %d b = %d\n",a, b); // swapped
     
    return(0);
}
 
void swap_by_value(int a, int b) // a copy of a and b 
{
    int temp;
     
    temp = a;
    a = b;
    b = temp;
}
 
void swap_by_address(int *a, int *b) // pointers to a and b
{
    int temp;
     
    temp = *a;
    *a = *b;
    *b = temp;
}
 
  
  
/*
  
run:
  
a = 3 b = 7
a = 7 b = 3
  
*/

 



answered May 5, 2017 by avibootz
edited Dec 5, 2024 by avibootz

Related questions

1 answer 105 views
1 answer 122 views
1 answer 141 views
1 answer 121 views
1 answer 97 views
...