C References (Call by Reference)

Passing by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function.


In call by reference, the operation performed on formal parameters, affects the value of actual parameters because all the operations performed on the value stored in the address of actual parameters.


Code:


  #include 

  void swapnum(int *var1, int *var2)
  {
  int tempnum ;
  tempnum = *var1;
  *var1 = *var2;
  *var2 = tempnum;
  }

  int main()
  {
  int num1 =35, num2 = 45;
  printf("Before swapping:");
  printf("\nnum value is %d", num1);
  printf("\nnum2 value is %d", num2);

  /*Calling swap function*/
  swapnum(&num1, &num2);
  printf("\nAfter swapping:");
  printf("\nnum value is %d", num1);
  printf("\nnum2 value is %d", num2);
  return 0;
  }


before swapping :

num1 value is 35

num2 value is 45

after swapping:

num1 value is 45

num2 value is 35

Explanation:

Here, we're utilizing call by reference to switch the integers. As you can see, after using the swapnum() function, the values of the variables changed since the addresses of the variables num1 and num2 were swapped.







© Copyright 2022 Advanced PLC. All rights reserved.