Jump to: navigation, search

Pass by reference is a term that describes a part of the semantics of function parameters. To pass by reference means that within the function, the formal parameter is or acts as an alias (reference) for the function argument - so pass by reference is only meaningful when the function's argument is a variable (note that "parameter" and "argument" have slightly different meanings - consult the link in the "See Also" section below).

Within the function, accesses of the formal parameter, either for reading or for writing, directly access the same variable that the caller of the function passed in as its argument.

C does not directly support pass by reference because it always uses pass by value, but a programmer can implement pass by reference by passing a pointer to the variable that the programmer wants passed by reference.

Quick examples

The program below

#include <stdio.h>
void foo(int *x);

int main(void) {
  int i = 5;
  printf("In main(): %d\n", i);
  printf("In main(): %d\n", i);

  return 0;

void foo(int *x) {
  printf("In foo(): %d\n", *x);
  *x = 10;
  printf("In foo(): %d\n", *x);


 In main(): 5
 In foo(): 5
 In foo(): 10
 In main(): 10

Notes on proper usage

Pass by reference and call by reference are synonyms and are specific terms of art that indicate direct syntactical support in the language. Referring to the C mechanism used in the example above - passing a pointer to a variable in order to access the variable within the function - as "pass by reference" is technically incorrect. This is because within the function the language's syntax requires the dereferencing operator to be applied to the pointer, whereas true pass by reference, such as supported by Pascal (parameters declared with var) and C++ (parameters declared with &), does not have that requirement. Better and more correct is to refer to the C mechanism as "passing a reference".

See also


Personal tools
Personal tools
not logged in