top | item 13659251

(no title)

marcoms | 9 years ago

Why not fixed-size ints - uint8_t, etc. from stdint.h? I've not been using C for a while, so I wonder what the viewpoints are regarding this.

discuss

order

jhallenworld|9 years ago

You typically want to use the native integer size for something like this, for the code to be more portable. The native integer size should really be int, but it's not defined as such in the standard. My preference at the moment:

off_t for file offsets

ptrdiff_t for memory offsets (vs. size_t for unsigned)

int for return flags

A problem with this is that printf does not have sizes to match these.

omtose|9 years ago

But then you get different behavior depending on the platform, which doesn't seem any more portable to me.

jwilk|9 years ago

For ptrdiff_t: "%td"

For size_t: "%zu"

There's no format for off_t, though. The best you can do is to typecast it to intmax_t, and then use "%jd".

beached_whale|9 years ago

there are also int_least8_t or what ever size and signedness too. or int_fast8_t. You explicitly state I want at least 8 bits or I want at least 8 bits but whatever is fastest.

Sean1708|9 years ago

Fixed sized integers are useful in two situations (that I can think of); if you're interfacing with a language that doesn't use the same integer size as your C compiler, or if you're relying on integers being a certain width (maybe you're casting between integers and non-integers, or writing a certain number of bytes to a binary file).

I doubt either of these situations come up when dealing with line sizes in a text editor.

datenwolf|9 years ago

And a third situation: Writing device drivers interfacing with hardware registers of specific sizes, although you should use `{u}int_least<N>_t` for that, to give the compiler some leeway with alignment.

jstelly|9 years ago

There are many cases where using fixed size types can save a significant amount of memory (and your application is constrained by memory on some platform) or CPU time (design to minimize cache misses happens all the time in high performance applications like games).

Neither of these situations is happening in a text editor application though.

wyldfire|9 years ago

Best of both worlds: uint_fast8_t / uint_least8_t gives you at least 256 discrete values and likely a native/optimal-register-width allocation.