/*
 * Compiler Writing – CSCI 4800 / CSCI 6800
 * Fall 2021
 * Clément Aubert
 * File under https://creativecommons.org/licenses/by/4.0/
 */

#include <stdio.h>
#include <stdlib.h>

/*
 * This small program illustrates
 * the difference between passing the reference
 * or the value of the argument to a function.
 */

void swap(int a, int b){
    int temp;
    temp = a;
    a = b;
    b = temp;
    printf("Inside swap,\n\ta is %d\n\tb is %d\n", a, b );
}

void plus_value(int a){
    a = a+1;
    printf("Inside plus_value,\n\ta is %d.\n", a);
}

void plus_reference(int* p){
// This function takes a pointer as argument.
// You can consult e.g. https://stackoverflow.com/q/5484624
// to learn more about this star notation.
    *p = *p+1;
// Means "the value pointed at by the pointer p
// should be incremented by 1."
//  p = p + 1;
// Would mean "the address needs to be incremented
// by (the space taken by) one int", so, "move to 
// the next memory location 1 int's lenghth".
// cf. https://stackoverflow.com/a/7886209 or
// https://stackoverflow.com/a/30743523
    printf("Inside plus_reference,\n\t*p is %d.\n", *p);
}

int main () {

   int a = 10;
   int b = 20;
 
   printf("/*/*/*/*/*/*/*/*/*/\n/* Swap example. */\n/*/*/*/*/*/*/*/*/*/\n");

   printf("Before swap,\n\ta is %d\n\tb is %d\n", a, b );
   /* calling a function *by value* to swap the values */
   swap(a, b);
   printf("After swap,\n\ta is %d\n\tb is %d\n", a, b );

   printf("\n\n/*/*/*/*/*/*/*/*/*/\n/* Plus example. */\n/*/*/*/*/*/*/*/*/*/\n");

   printf("Before plus_value,\n\ta is %d\n", a);
   /* calling a function *by value* to add one to the value */
   plus_value(a);
   printf("After plus_value,\n\ta is %d\n", a);

   printf("Before plus_reference,\n\ta is %d\n", a);
   /* calling a function *by reference* to add one to the value */
   plus_reference(&a); // Note the way the argument is given: we're
   // not passing a, but the address of a.
   printf("After plus_reference,\n\ta is %d\n", a);

   exit(EXIT_SUCCESS);
}
