• Home
  • 6.8 Passing Arguments by Value

6.8 Passing Arguments by Value

View Categories

6.8 Passing Arguments by Value

C passes function arguments by value. Each parameter receives a copy of the argument’s value, so modifying the parameter does not directly modify the original variable in the calling function.

#include <stdio.h>

void changeValue(int number)
{
    number = 100;
    printf("Inside function: %d\n", number);
}

int main(void)
{
    int value = 10;

    changeValue(value);

    printf("Inside main: %d\n", value);

    return 0;
}

Example Output #

Inside function: 100
Inside main: 10

Explanation #

The variable value is initialized to 10:

int value = 10;

When changeValue(value) is called, the value of value is copied into the parameter number.

void changeValue(int number)
{
    number = 100;
}

The assignment changes only the local parameter number. The original variable value remains unchanged.

Argument Passing #

Operation Value
Initial value of value 10
Initial value copied into number 10
number after assignment 100
value after function returns 10

C uses pass-by-value for all function arguments, including pointer arguments. A pointer’s value—the address it stores—is copied when passed to a function. A function can use that copied address to modify the object it points to, which is covered in the next lesson.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *