Skip to content

Instantly share code, notes, and snippets.

@litzomatic
Created June 27, 2012 15:25
Show Gist options
  • Save litzomatic/3004820 to your computer and use it in GitHub Desktop.
Save litzomatic/3004820 to your computer and use it in GitHub Desktop.
Useful ammo for any pass by value debates (Java, Python, etc)
#include <stdio.h>
#include <malloc.h>
void value_swap(int, int);
void reference_swap(int*, int*);
void memory_swap(int*, int*);
int main(int argc, char **argv)
{
int* a = malloc(sizeof(int));
int* b = malloc(sizeof(int));
*a = 0;
*b = 1;
printf("Initial values\n");
printf("a: %d b: %d\n", *a, *b);
value_swap(*a, *b);
printf("After value swap\n");
printf("a: %d b: %d\n", *a, *b);
reference_swap(a, b);
printf("After reference swap\n");
printf("a: %d b: %d\n", *a, *b);
memory_swap(a, b);
printf("After memory swap\n");
printf("a: %d b: %d\n", *a, *b);
return 0;
}
/* Pass by value */
void value_swap(int a, int b)
{
int* temp;
*temp = a;
a = b;
b = *temp;
printf("In value swap\n");
printf("a: %d b: %d\n", a, b);
}
/* Reference is also passed by value */
void reference_swap(int* a, int* b)
{
int* temp;
temp = a;
a = b;
b = temp;
printf("In reference swap\n");
printf("a: %d b: %d\n", *a, *b);
}
/* However, with a reference we can change the memory it points at */
void memory_swap(int* a, int* b)
{
int* temp;
*temp = *a;
*a = *b;
*b = *temp;
printf("In memory swap\n");
printf("a: %d b: %d\n", *a, *b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment