S
suman kar
Of course you are right in saying that a runtime operator for
getting an object's type doesn't make much sense in C.
I am not sure, however, if I would characterize gcc's typeof()
as a "band-aid for macros". Calling it band-aid implies that
there may be a better solution in sight. Look at:
#define swap(a,b) do \
{ typeof(a) swap_tmp = a; a = b; b = swap_tmp; } while(0)
The alternative is to write a different swap macro/function for
each different type. Which is the cleaner? Which is the band-aid?
One more alternative:reading up on K&R, they did it years ago without
any typeof operator.Hintass the type as a parameter.
A more interesting and useful application of a typeof()
construct would be in the dynamic allocation of two-dimensional
arrays. Instead of having to supply multiple functions such as:
double **make_matrix_double (size_t m, size_t n);
int **make_matrix_int (size_t m, size_t n);
complex **make_matrix_complex (size_t m, size_t n);
mystruct **make_matrix_mystruct(size_t m, size_t n);
you may write a single make_matrix() macro for all types.
Very handy for numerical analysts working with matrix algebra.
I wouldn't dismiss this an "odd occasion where it is useful".
HTH.
Suman.