Diference between passing values byRef or byVal in c

This code shows the diference between passing a value to a function byVal vs byRef, in this example the swap function only works when one pass the value byRef, Try it.


#include<stdio.h>

void swap(int a, int b);

int main()
{
int a = 1;
int b = 2;
printf("before swap a = %d\n", a);
printf("before swap b = %d\n", b);
swap(a, b);
printf("after swap a = %d\n", a);
printf("after swap b = %d\n", b);
}

void swap(int a, int b) {
int tmp = a;
a = b;
 b = tmp;
}


#include<stdio.h>
void swap(int *a, int *b);
 
int main()
{
    int a = 1;
    int b = 2;
    printf("before swap a = %d\n", a);
    printf("before swap b = %d\n", b);    
    swap(&a, &b);
    printf("after swap a = %d\n", a);
    printf("after swap b = %d\n", b);
}

void swap(int *a, int *b) {
  int tmp = *a;
  *a = *b;
  *b = tmp;
}
 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s