On Fri, 11 Jul 2003 17:48:29 +0100
John Lamb
Here's a question for anyone who knows about C/C++ technicalities.
I recently noticed that gcc/g++ allows the following for ints or any other builtin type.
type_name function( int );
type_name function( const int x){ ... }
i.e. the declaration and definition parameter types are nominally different. Is this correct in ISO C++? I couldn't find any mention of this in Stroustrup.
It seems eminently sensible to me that this should be allowed. I often
want the compiler to check that x is const within function but don't need to declare a variable const if it's passed by value. OTOH C++ allows overloading -
type_name function( const int& x ){ ... }
type_name function( int& x ){ ... }
can be defined differently. const int x is, as you mentioned, passed by value, but also does not allow the function to set x to another value (in C and C++). This is quite different from the C++ call by reference. In the pass by reference model, making chages to x side effects the caller's x. So, "const int& x" is much more important than is const int x. Also, in both C and C++, making a pointer constant: type_name function( const int *x ){ ... } This makes the int pointed to by x const, but the pointer, x, can be set and reused within the function.
Most of the C library function use const when that function is not going
to side effect:
eg. char *strcpy(char *d, const char *s);
This means that strcpy will not side effect the (source) string pointed
to by s.
--
Jerry Feldman