Advertisement
ProgtestovyManiak

anIdiotsGuideToProgtest_returning.c

Nov 14th, 2018
425
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.66 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. //x is passed as pointer to memory where actual value is stored
  4. void addOneUsingPointers(int *x) {
  5.   // here we add to the value x is pointing to
  6.   // x is currently pointing at "a" variable in main function
  7.   // this means that we add 1 to "a"
  8.   (*x)++;  // x is address of memory, (*x) is the actual value
  9. }
  10.  
  11. //x is passed as copy of value
  12. void addWithoutUsingPointers(int x) {
  13.   x++;  //value was added but not returned
  14. }
  15.  
  16. // x passed as copy of value
  17. // starts with "int" which is type of the value we want to return
  18. int addValueWithReturn(int x) {
  19.   x++;
  20.   return x;
  21. }
  22.  
  23. int main() {
  24.   int a=0;
  25.   printf("starting value of a: %d\n", a);
  26.   // we pass the pointer to the value "a" instead of the actual value
  27.   // this means that we can modify the "a" variable without using "return"
  28.   addOneUsingPointers(&a);
  29.   printf("one was added to a: %d\n", a);
  30.  
  31.   // here we pass value to the function, but no modifications can be made within
  32.   // the function, since there is no way for the function to access the actual variable
  33.   // (it has only a copy of it)
  34.   addWithoutUsingPointers(a);
  35.   printf("nothing was added to a: %d\n", a);
  36.  
  37.   // here we send a copy of variable "a" and use "return" to get the value back from the function
  38.   // the value in "a" is not changed since we do not save the returned value to any other variable
  39.   addValueWithReturn(a);
  40.   printf("value was properly returned but not saved, a: %d\n", a);
  41.  
  42.   // here we save the returned value back to variable "a" so it is changed and returned correctly
  43.   a = addValueWithReturn(a);
  44.   printf("value properly returned and properly saved, a: %d\n", a);
  45.  
  46.  
  47.   return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement