Bifalgorithm post · Computer science one · Passing By Reference

How can pointers be used to pass variables by reference?

How can pointers be used to pass variables by reference? (Computer science one · Passing By Reference) — "Now that we have the ability to reference a memory lo…

Ideas in this flowchart

  • Passing variables by reference with pointers
  • Pointers allow functions to reference memory locations
  • The asterisk syntax identifies pointer variables
  • The dereferencing operator accesses or modifies the pointed-to value
  • Functions demonstrate passing values and references
  • Function prototypes declare sum and swap
  • sum receives two values by value and a third variable by reference
  • sum calculates a plus b and stores the result through c
  • swap receives two variables by reference
  • swap uses a temporary variable to exchange the pointed-to values
Feed/

How can pointers be used to pass variables by reference?

No cover

Channel

Computer science one

1 page

"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 }"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.