I'm learning C from Robert C. Seacord's "Effective C" book, and there's an introduction to pointers and call-by-value vs. call-by-reference by writing a function that swaps the values of variables (called swap). The end result is:
#include <stdio.h>
void swap(int *pa, int *pb) {
int t = *pa;
*pa = *pb;
*pb = t;
}
int main(void) {
int a = 21;
int b = 17;
swap(&a, &b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
This is all well and clearly explained but after I read this part,
*pa = *pb;This dereferences the pointer
pb, reads the referenced value, dereferences the pointerpa, and then overwrites the value at the location referenced bypawith the value referenced bypb.
I started thinking: would it be possible to make variable a point to the memory range holding the value pointed to by variable b (and vice versa) instead of overwriting the memory ranges of a and b?
At least, based on little what I know, "in C, variables are human-readable names for the computer's memory addresses used by a running program". I understand that this is a contrived example (found also in many other tutorials as well) but still wondering whether the overwriting of address ranges is wasteful/inefficient.
Tried to google this but kept getting irrelevant results; probably because I wasn't using the right terms... I would probably find the answer in a couple of weeks, but had to put this in writing as it was constantly gnawing at me. Thank you!