Sunday, August 8, 2010

Pointer cause decay, references do not.

Decay means loss of type information. In C and C++, an array name 'decays' to pointer to the first element. The information lost is basically the number of elements in the array. This difference should be manifested by sizeof() operator in function f() and g(). References keep that information with them. such as 'constness' of int. Function names are also said to 'decay' into pointer to the function if only function name is used. But such a function pointer retains, I think, everything about the function signature: parameter types and function return type; even in C.

With following declarations,

template < typename T > void f (T);
template < typename T > void g (T &);

and with these declarations,

double x[20];
int const seven = 7;

f(x); T is double *
g(x); T is double [20]
f(seven); T is int
g(seven); T is int const
f(7); T is int
g(7); T is int, ERROR can't pass 7 to int&

Therefore, pointer cause decay, references do not.

0 comments:

Post a Comment