c
  1. c-call-value-reference

C Call: Value & Reference

Explanation

In C programming, there are two ways of passing values to functions - by value and by reference. When a variable is passed by value, a copy of the variable's value is passed to the function. When a variable is passed by reference, a pointer to the variable's memory address is passed to the function.

Syntax

Passing a variable by value:

void functionName(int a);

Passing a variable by reference:

void functionName(int *a);

Example

Passing a variable by value:

#include <stdio.h>

void doubleNum(int num) {
  num = num * 2;
  printf("The doubled value is: %d\n", num);
}

int main() {
  int num = 5;
  printf("The original value is: %d\n", num);
  doubleNum(num);
  printf("The original value is still: %d\n", num);
  return 0;
}

Passing a variable by reference:

#include <stdio.h>

void doubleNum(int *num) {
  *num = *num * 2;
  printf("The doubled value is: %d\n", *num);
}

int main() {
  int num = 5;
  printf("The original value is: %d\n", num);
  doubleNum(&num);
  printf("The original value is now: %d\n", num);
  return 0; 
}

Output

Output for the by value example will be:

The original value is: 5
The doubled value is: 10
The original value is still: 5

Output for the by reference example will be:

The original value is: 5
The doubled value is: 10
The original value is now: 10

Use

Passing variables by value is useful when you do not want the function to modify the original variable's value. Passing variables by reference is useful when you want the function to modify the original value.

Important Points

  • When a variable is passed by value, a copy of the variable's value is passed to the function. The function cannot modify the original value.
  • When a variable is passed by reference, a pointer to the variable's memory address is passed to the function. The function can modify the original value.
  • Passing by reference can be more efficient for large data structures because a copy of the structure does not need to be created.

Summary

Understanding the differences between passing variables by value and by reference in C programming is important when designing functions. Passing by value is useful when you do not want the original variable's value to be modified, while passing by reference is useful when you want the function to modify the original value. Remembering these basic principles can help you design more efficient programs that make good use of memory and are reliable in their operations.

Published on: