q for the C hackers

Erik Price eprice at ptc.com
Tue Aug 19 11:57:42 EDT 2003


Tom Fogal wrote:

> The bit about memory addresses instead of some large value is entirely correct.
> Practically however, this will only be better when passing a value larger than
> the register size of the architecture you are on. For instance, on ix86 linux,
> all pointers are 32-bit integers. Thus passing a constant reference to another
> integer still means you have to pass an integer to the function, thus saving
> nothing.
> This is commonly used when you have a large record or object.

Okay, that makes sense.  Fundamentally, there seems to be little 
difference between passing a pointer to an object, and passing the 
address of the variable holding that object's value.  I seem to recall 
that there literally *is* no difference, actually -- a pointer is just 
the address of a variable IIRC.  But I'm glad you confirmed this.

> The const is purely optional; you could just as easily remember yourself that
> 'hey, i dont want to change that value in this function' and simply not do it.
> The justification i was given for such usage is that someone who is not you
> can quickly look at the function header/prototype and see, 'oh, this value is
> const, it wont change when i pass it to the function'.

I had forgotten about the header/prototype.  Yes, it seems desirable to 
use 'const' in any function declaration that doesn't modify the 
parameters, as a way of communicating to others that the parameters will 
not be modified.  I will get in the habit of using 'const' in function 
parameters.

(I don't know C++, but let me take a guess at something -- that, in C++ 
making a passed reference a constant by using 'const' in a function 
declaration doesn't make any assurances that the object which the 
reference points to will not be modified, only that the reference itself 
will not change.  In other words, it is much like passing a 'final' 
reference in Java.)

> Btw, a similar gain can be obtained via pointers, so C programmers aren't
> left out =).

And this is what I am more used to seeing -- it appears that usually a 
function will be written to accept a pointer, rather than a value's 
address, even if they are the same thing.

>>is a reference, and that this is different from the address of 'val'?  I 
>>thought that this meant "the address of 'val'".
> 
> 
> Oh yes, this is a source of much confusion. You see, C++ introduced this idea
> called a 'reference', which, for all intents and purposes is a pointer, but
> you dont have to dereference it as such.

I think I'm going to stay away from C++ for the moment, at least until I 
have a better grip on C and Objective-C.  (Coming from a Java 
perspective, Objective-C seems a little more straightforward to me than 
C++, esp since it doesn't seem to have changed any of the rules of C.)

Thanks again Tom and everyone.


Erik




More information about the gnhlug-discuss mailing list