C Pass by Value

Summary: in this tutorial, you’ll learn the differences between function parameters and arguments and how to pass arguments to function by values.

Parameters vs. Arguments

In the function tutorial, you find that the terms parameters and arguments are used interchangeably. In fact, they’re different.

When defining a function, you specify the function parameters. However, when calling a function, you pass the arguments to it. For example:

int square(int n);
Code language: C++ (cpp)

In the square() function, n is a function parameter because you specify it in the function definition.

When you call the square() function:

int result = square(10);
Code language: C++ (cpp)

… the number 10 is a function argument.

In C, you have two way to pass arguments to a function:

  1. Passing arguments by values
  2. Passing arguments by references

In this tutorial, you’ll focus on how to pass arguments to a function by values.

Pass by value

See the following example:

#include <stdio.h> int square(int n); int main() { int n = 10; int result = square(n); printf("n in the main function %d\n", n); printf("result=%d\n", result); } int square(int n) { // for demo purpose only n = n * n; printf("n in the square function:%d\n", n); // return n return n; }
Code language: C++ (cpp)

Output:

n in the square function:100 n in the main function 10 result=100
Code language: C++ (cpp)

How it works.

First, define the square() function that accepts an integer and returns the square of the integer:

int square(int n) { n = n * n; return n; }
Code language: C++ (cpp)

Second, define the variable n and initialize its value to 10:

int n = 10;
Code language: C++ (cpp)

Third, pass the variable n to the square function:

int result = square(n);
Code language: C++ (cpp)

When we pass the variable n to the square() function, the square() function makes a copy of n and works on that copy. And then, the square() function returns the square the variable n.

Even though we change the value of n inside the square() function, the change only affects the copy, not the original variable.

In conclusion, when you pass an argument by value to a function, the function makes a copy of that argument and works on that copy. The changes to the copy do not affect the original value.

In practice, you should use pass-by-value when the called function doesn’t need to modify the values of the original varaibles.

By default, all arguments are passed by values except when you explicitly use the pass-by-reference via the pointers and address operator (&).

Summary

  • Parameters are variables that you specify in the function prototype or definition. Arguments are variables that you pass to the function.
  • When you pass an argument to a function by value, the function makes a copy of that argument. The changes that the function makes to the argument do not affect the original argument. This is the default behavior.
Was this tutorial helpful ?