Explaining pass-by-value and pass-by-reference in C for 1st year IT student

explaining-pass-by-value-and-pass-by-reference-in-c-for-1st-year-it-student

TL;DR

  • Pass-by-value: value of parameters in a function will NOT be changed after function is called.
  • Pass-by-reference: value of parameters in a function MIGHT be changed after function is called (when they’re updated in the function).

Pass-by-value

When you declare a variable, it allocates a memory for that variable. When you call a function foo(variable_name), it means you pass the value of that variable in the memory to a function. Whatever the function does, it doesn’t affect to the memory of the variable. Value of the variable remains the same.

Example code:

#include 

void foo(int x);

int main() {
    int a = 1;

    foo(a);

    printf("a: %d", a); //a: 1

    return 0;
}

void foo(int x) {
    x = 5;
}

In the sample code above, when you call foo(a):

  • It actually call foo(1)
  • In the foo(int x) function, it allocates a new memory for x, then sets x to 5
  • In the main function, a is still 1

Pass-by-reference

As mentioned, when you declare a variable, it allocates a memory for that variable. Memory has memory address. When you call a function foo(variable_memory_address), it means you pass the memory address to a function. If you change the value of the memory in the function, you actually update the value in the memory of the variable. That’s why variable value will be changed.

Example code:

#include 

void foo(int* px);

int main() {
    int a = 1;

    foo(&a);

    printf("a: %d", a); //a: 5

    return 0;
}

void foo(int* px) {
    *px = 5;
}

In the sample code above, when you call foo(&a):

  • It actually call foo(0xAB) (assumed memory address of variable a is 0xAB)
  • In the foo(int* px) function, it creates a pointer px, and px points to 0xAB
  • When you set *px = 5, it means it sets the value at memory _0xAB _to 5
  • Then in the main function, as value in the memory of variable a was changed to 5, value of a now is 5.
Total
1
Shares
Leave a Reply

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

Previous Post
tailwindcss-explained!

TailwindCSS Explained!

Next Post
cdk-aws-cloudwatch-evidently-demo

CDK AWS Cloudwatch Evidently Demo

Related Posts