C Programming

⌘K
  1. Home
  2. Docs
  3. C Programming
  4. Functions
  5. Passing Arguments by Value and Address

Passing Arguments by Value and Address

Passing arguments by value means the function receives a copy of the actual value passed to it. Any modifications made to the parameter inside the function do not affect the original variable.

Key Features:

  • The original variable remains unchanged.
  • Safe from unintended modifications.
  • Used when you don’t need to modify the original data.

Example:

#include <stdio.h>

void modify(int x) {
    x = x + 10;
    printf("Inside function: x = %d\n", x);
}

int main() {
    int a = 5;
    modify(a);
    printf("Outside function: a = %d\n", a); // Value remains 5
    return 0;
}

Output:

Inside function: x = 15
Outside function: a = 5

Passing arguments by address (also called pass by reference) means passing the memory address of the variable to the function.

  • Any changes made to the parameter inside the function directly modify the original variable.

    Key Features:

    • The original variable can be changed.
    • Used when a function needs to modify the original data.
    • Achieved using pointers in C.

    Example:

    #include <stdio.h>
    
    void modify(int *x) {
        *x = *x + 10;
        printf("Inside function: x = %d\n", *x);
    }
    
    int main() {
        int a = 5;
        modify(&a);
        printf("Outside function: a = %d\n", a); // Value becomes 15
        return 0;
    }

    Output:

    Inside function: x = 15
    Outside function: a = 15

    How can we help?

    Leave a Reply

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