Why can't we pass an integer like this too? Without creating another copy of it?
You can. You can pass the address object x
by passing &x
(as long as x
was not declared with the register
storage class keyword). The called function should be defined in a corresponding way, to accept a pointer to that type of object.
If want to pass a value that is not currently in an object, you can use a compound literal to create an object: & (int) { 3 }
will create an int
object, initialize it with the value three, and take its address.
Why waste four bytes when the alternative way isn't even that complicated?
Pointers take at least four bytes in current typical systems, eight bytes in typical 64-bit platforms. So, if you use a pointer, instead of having a four-byte int
, you have both a four-byte int
and a four- or eight-byte pointer. Also, int
values and pointers are commonly passed in processor registers, not memory, so they would not take any less space if you did not use the whole register.
Why not use an integer pointer?
Since a pointer is not typically smaller than an int
, there is no space savings in passing it, and it may take a little extra work to create the address of something rather than using its value directly. It is also likely to cause extra work in the called routine, as it has to use the address to fetch the value from memory instead of using directly from the register it was passed in.
If one is worried about one of the developers changing the value, then make it a constant integer pointer.
Passing a const
-qualified pointer to an object does not guarantee the called function will not change it. const
was added to the C language late, so it is not fully integrated into the type system and serves more as advice and help in writing correct code than as total enforcement of prohibiting changes.