C/C++ Values, Pointers, and References
- 1 minutes read - 205 wordsI had an embarrassing realization: While C does have an address-of operator, it does not include reference variable or pass-by-reference syntax. It’s embarrassing because I should have realized that it was a C++ invention; I guess some of my “C” code actually really has been C++ code.
For future reference, here’s the current summary of my understanding:
var | *var | &var | ||
---|---|---|---|---|
int xv=3; | value | invalid | memory location of value | |
int *xp=&xv; | memory location | value | memory location of pointer. | |
int &xr=xr; | value | invalid | memory location of value | (all invalid in C) |
As one other note, there are three ways you can pass things in C:
void square_value(int x) { x = x*x; }
void square_pointer(int *x) { if (x != NULL) *x = *x * *x; }
void square_reference(int &x) { x = x * x; }
Of course, the first doesn’t update x. The next two do, but the pointer version is wordier because we have to check for null, whereas the reference version is legal by default. The point of the pointer and reference versions is that we don’t need to create a copy of the object. That doesn’t matter for integers (and in fact even makes integers slower!) but matters a lot for objects.