-1

In page 15 of my lecture slide, there is an example.

int x = 10;
increment_int(x); // can’t change the value of x
increment2_int(&x); // can change the value of x

I don't understand why the first function increment_int(x) can't change the value of x. Though I don't know what those functions exactly do, I guess they are incrementing some amount to the argument.

user8314628
  • 1,952
  • 2
  • 22
  • 46

1 Answers1

2
  • increment_int is pass by value. If the function increment_int changes the value of its parameter, it is only reflected in its local copy. The caller doesn't see the change.
  • increment2_int is pass by reference. You pass the address of x rather the value of x to this function. This function changes the value of at the specified address which is reflected on the caller side too.
VHS
  • 9,534
  • 3
  • 19
  • 43
  • 1
    perhaps a nitpick, but _everything_ in C is pass-by-value. A pointer to `x` is passed to `increment2_int`. Since it's pass-by-value, a copy of that pointer is made inside `increment2_int`, this pointer and `&x` point to the same thing,, so when `x` is dereferenced in `increment2_int`, it points to `x` in the caller. – yano Apr 09 '19 at 02:35