Skip to content

Instantly share code, notes, and snippets.

@jkwill87
Created January 28, 2016 22:13
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jkwill87/5c71cdb599e7a719a4d0 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
/**
* grade2.c
*
* this program will allocate memory for an integer on the heap, and demonstrate
* how C treats values passed by value as opposed to by reference.
*/
int finalGradeValue (int grade, int bonus); //grade passed by value
int finalGradeReference (int* grade, int bonus); //grade passed by reference
int main() {
int* grade = malloc (sizeof (int));
*grade = 45;
finalGradeValue (*grade, 5); // passed value not modified; notice '*'
printf ("Your final mark is %d. ", *grade);
puts (*grade < 50 ? "You failed!" : "You passed!");
finalGradeReference (grade, 5); // passed value modified
printf ("Your final mark is %d. ", *grade);
puts (*grade < 50 ? "You failed!" : "You passed!");
free (grade);
return 0;
}
int finalGradeValue (int grade, int bonus) {
grade = grade + bonus;
return grade;
}
int finalGradeReference (int* grade, int bonus) {
*grade = *grade + bonus;
return *grade;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment