Skip to content

Instantly share code, notes, and snippets.

@rachtsingh
Created December 30, 2016 01:09
Show Gist options
  • Save rachtsingh/8f4b42dbda016dd2bb9de8745b8a2bb3 to your computer and use it in GitHub Desktop.
Save rachtsingh/8f4b42dbda016dd2bb9de8745b8a2bb3 to your computer and use it in GitHub Desktop.
explanation of passing by value
#include <stdio.h>
void swap_values_1(int p, int q) {
printf("where are the local variables in this function allocated? p: %p, q: %p\n", &p, &q);
int tmp = q;
q = p;
p = tmp;
}
void swap_values_2(int *m, int *n) {
printf("the values of m and n: m: %p, n: %p\n", m, n);
// note! this is different from where m and n are themselves allocated! it's where they point to!
printf("where m and n are allocated: m: %p, n: %p\n", &m, &n);
// and this is the value at the address they point to:
printf("values at those addresses: %p: %d, %p: %d\n", m, *m, n, *n);
// ok let's swap
int tmp = *n;
*n = *m;
*m = tmp;
}
void print_values(int x, int y) {
printf("a: %d\n", x);
printf("b: %d\n", y);
}
int main() {
int a = 5;
int b = 10;
printf("where are a and b allocated? a: %p, b: %p\n", &a, &b);
print_values(a, b);
// try swapping
swap_values_1(a, b);
printf("After swap 1:\n");
print_values(a, b);
// try swapping again
swap_values_2(&a, &b);
printf("After swap 2:\n");
print_values(a, b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment