#include int func(int *a, int b) { printf("a: %p\n", a); *a = *a + b; return *a; } int main() { int value = 10; int result; printf("prima vale: %d\n", value); printf("indirizzo: %p\n", &value); result = func(&value, 10); printf("dopo vale: %d\n", value); printf("risultato: %d\n", result); printf("prima vale: %d\n", value); result = func(&value, 15); printf("dopo vale: %d\n", value); printf("risultato: %d\n", result); return(0); } /* * The second way to pass a parameter is "by reference". * * You pass a parameter by reference whenever you pass a pointer instead * of a value. * * The function can change the value of the parameter outside its own * scope. * * Using the dereference operator (*) the programmer can write data at the * memory address (pointer) of a variable from within the function. * Since the address of the variable is the same both inside and outside * the scope of the function, then the value is changed program-wide. */ /* * E.g: * * int func(int *apointer) // the function takes a pointer argument! * { * *apointer = ...; // changing the value at the specified address! * * // the change is visible within the whole memory space of the program! * ... * } * * int myvalue = ...; * ... * * func(&myvalue); // passing the addres! * // now the value of "myvalue" has changed! *... * */ /* * There are 3 reasons to pass an argument by reference: * * 1) You want a function to update the value of a variable, * * e.g. add_income(&total, amount); * * (add an amount to the total incomes). * * 2) You need your function to "return" more than one value, * * e.g.: solve_triangle(A, B, C, &surface, &perimeter); * * (given the lengths of the triangle sides A, B, and C calculate * its surface and perimeter). * * 3) You are forced to! (e.g.: when passing arrays, see "array.c"). */ /* * This function has 2 arguments: the first is passed by reference (it's * a pointer), the second is passed by value. * * The value at the memory address identified by the first parameter is * incremented by the value of the second. * * The value of the sum is returned. */