Re: defining the size_t type



lubomir dobsik <l.dobsik@xxxxxxxxx> writes:
hi, i have seen an interesting thing:

#if sizeof((char*)0 - (char*)0) == sizeof(unsigned int)
typedef unsigned int size_t;
#elif sizeof((char*)0 - (char*)0) == sizeof(unsigned long)
typedef unsigned long size_t;
#elif sizeof((char*)0 - (char*)0) == sizeof(unsigned long long)
typedef unsigned long long size_t;
#endif

is this way of defining the size_t portable?

No, for all the reasons that have already been mentioned. Where did
you see it?

If you're not writing an implementation, then you don't need to define
size_t; the implementation will do it for you.

If you are writing an implementation, you don't need a portable
definition. You can use whatever compiler-specific magic you like, as
long as it produces the correct results. If you happen to know that
your preprocessor handles sizeof (it's not required to, and I'm not
certain it's allowed to), then you can take advantage of that, though
as Richard Tobin mentions, ``(sizeof sizeof 0)'' would make more
sense.

The only context where the above would make sense is if you're writing
a <stddef.h> to be used with several different implementations (say,
the same compiler on several different platforms). But even then,
there are likely to be cleaner ways to do it.

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.



Relevant Pages