Skip to content

Instantly share code, notes, and snippets.

@felixvd
Last active June 19, 2020 10:32
Show Gist options
  • Save felixvd/24c5433e7f2228e2a3e550cf77738e25 to your computer and use it in GitHub Desktop.
Save felixvd/24c5433e7f2228e2a3e550cf77738e25 to your computer and use it in GitHub Desktop.
Pointer and reference example (C++)
void add_one_to_int(int& number)
{
// This increases the value of the parameter.
// The value will persist outside of the function, because the reference is passed,
// so the memory address is used.
number++;
}
void add_one_to_int_using_pointer(int* number_pointer)
{
// This function also increases the value of the parameter by accessing the
// memory location.
*number_pointer++;
}
int main()
{
int num = 0;
int* num_pointer;
*num_pointer = 0;
for (int i = 0; i < 5; i++)
{
add_one_to_int(num);
add_one_to_int_using_pointer(num_pointer);
}
printf("num, num_pointer = %d, %d", num, *num_pointer);
return 1;
}
// === INCORRECT EXAMPLES:
void add_one_to_int_THE_WRONG_WAY(int number)
{
// This will not increase the value outside of the function, since the function
// creates a copy of the input parameter.
number++;
}
void add_one_to_int_using_pointer_THE_WRONG_WAY(int* number_pointer)
{
// This function increases not the value at the address, but the memory address itself.
// It also uses a copy of the memory address (a copy of the pointer variable),
// so nothing makes sense about this.
number_pointer++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment