This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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