NetBSD-Users archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: C portability question

On 12-May-08, at 6:08 PM, James K. Lowden wrote:

Greg A. Woods; Planix, Inc. wrote:
        printf("%" PRId64 "\n", (int64_t) var);

Gah! Not to disagree, because I don't, but my elegance detector just had a hissy fit. Why didn't the inventors of off_t consider printf? Or even size_t, for that matter? (Even the above "standard" approach will fail
when off_t is 128 bits.)

When I deal with this stuff, I find myself wondering if we don't need an updated itoa. Wouldn't the code be more portable if libc defined e.g.,

        const char * off_ttoa(off_t in, char a[] out);

I suppose -- like it or not though C just isn't object oriented and neither is its data type system very sophisticated. The way you suggest would allow even doing away with printf() [and scanf()], but would require everyone devising a new type to write at least one [two] conversion functions, and with a somewhat more sophisticated interface if you want to support different number bases and/or units, for example.

At least for the most part we can make some assumptions about derivations of the base types (you pretty much have to know if a type is an int or pointer or struct/union to use it, for example) and then use casts to make sure they match the size of the type the printf() specifier expects.

The conversion to intmax_t and use of PRIdMAX as was suggested is perhaps safest and easiest, but I feel its wasteful (even if only in elegance). Finding the size of these types at compile time and using the exact match seems best to me, and it could even be done at run time, though that seem silly. If there was ever anything I wanted the C pre-processor to be a direct part of the language for it would be to allow sizeof() in #if expressions.

                                        Greg A. Woods; Planix, Inc.

Home | Main Index | Thread Index | Old Index