Return to Examples

C Programs:  (no Pass-By-Reference)
Pass-By-Value: 

#include <stdio.h>

void swap1(int a, int b)
{
  int temp = a;

  printf(" Beginning of subprogram\n");
  printf("a= %d \n", a);
  printf("b= %d \n", b);
  a = b;
  b = temp;
  printf(" Ending of subprogram\n");
  printf("a= %d \n", a);
  printf("b= %d \n", b);
}

main()
{
 int c=1;
 int d=0;

 printf("Before call  \n");
 printf("c= %d \n", c );
 printf("d= %d \n", d);
 swap1(c, d);
 printf("After call \n");
 printf("c= %d \n", c );
 printf("d= %d \n", d);
}
The output will be
Before call
c= 1
d= 0
 Beginning of subprogram
a= 1
b= 0
 Ending of subprogram
a= 0
b= 1
After call
c= 1
d= 0
Pass-By-Pointers:
#include <stdio.h>

void swap2(int *a, int *b)
{
  int temp = *a;

  printf(" Beginning of subprogram\n");
  printf("a= %d \n", *a);
  printf("b= %d \n", *b);
  *a = *b;
  *b = temp;
  printf(" Ending of subprogram\n");
  printf("a= %d \n", *a);
  printf("b= %d \n", *b);
}

main()
{
 int c=1;
 int d=0;

 printf("Before call  \n");
 printf("c= %d \n", c );
 printf("d= %d \n", d);
 swap2(&c, &d);
 printf("After call \n");
 printf("c= %d \n", c );
 printf("d= %d \n", d);
}
The output will be
Before call
c= 1
d= 0
 Beginning of subprogram
a= 1
b= 0
 Ending of subprogram
a= 0
b= 1
After call
c= 0
d= 1