Concept
How can pointers be used to pass variables by reference?
ComputerScienceOne / Passing By Reference
"Now that we have the ability to reference a memory location using pointers, we can write functions that pass variables by reference. To do so, we use the same asterisk syntax used with pointer variables. In the function definitions, we can use the dereferencing operator to access or modify the value stored in the variable pointed to by the pointer.\n\n1 //prototypes\n\n2 /**\n\n3 * This function sums the first two variables (passed by\n\n4 * value) and places the result into the third variable\n\n5 * (passed by reference).\n\n6 */\n\n7 void sum(int a, int b, int *c);\n\n8\n\n9 /**\n\n10 * This function swaps the values stored in the\n\n11 * two variables passed by reference.\n\n12 */\n\n13 void swap(int *a, int *b);\n\n1 void sum(int a, int b, int *c) {\n\n2 int x = a + b;\n\n3 *c = x;\n\n4 return;\n\n5 }\n\n6\n\n7 void swap(int *a, int *b) {\n\n8 int temp = *a;\n\n9 *a = *b;\n\n10 *b = temp;\n\n11 return;\n\n12 }"
Related Ideas
- How do pointers pass values by reference in C?ComputerScienceOne · Function Pointers
- How does PHP pass arguments by reference?ComputerScienceOne · Passing By Reference
- How can functions be assigned to variables and invoked as callbacks?ComputerScienceOne · Function Pointers
- How does Java handle passing primitive and object types to methods?ComputerScienceOne · Passing By Reference
- What topics are covered in error handling?ComputerScienceOne · Function Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . .