Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- //x is passed as pointer to memory where actual value is stored
- void addOneUsingPointers(int *x) {
- // here we add to the value x is pointing to
- // x is currently pointing at "a" variable in main function
- // this means that we add 1 to "a"
- (*x)++; // x is address of memory, (*x) is the actual value
- }
- //x is passed as copy of value
- void addWithoutUsingPointers(int x) {
- x++; //value was added but not returned
- }
- // x passed as copy of value
- // starts with "int" which is type of the value we want to return
- int addValueWithReturn(int x) {
- x++;
- return x;
- }
- int main() {
- int a=0;
- printf("starting value of a: %d\n", a);
- // we pass the pointer to the value "a" instead of the actual value
- // this means that we can modify the "a" variable without using "return"
- addOneUsingPointers(&a);
- printf("one was added to a: %d\n", a);
- // here we pass value to the function, but no modifications can be made within
- // the function, since there is no way for the function to access the actual variable
- // (it has only a copy of it)
- addWithoutUsingPointers(a);
- printf("nothing was added to a: %d\n", a);
- // here we send a copy of variable "a" and use "return" to get the value back from the function
- // the value in "a" is not changed since we do not save the returned value to any other variable
- addValueWithReturn(a);
- printf("value was properly returned but not saved, a: %d\n", a);
- // here we save the returned value back to variable "a" so it is changed and returned correctly
- a = addValueWithReturn(a);
- printf("value properly returned and properly saved, a: %d\n", a);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement