Hacker News new | ask | show | jobs
by accatyyc 3409 days ago
I'm in the "never use fixed size integers unless needed"-camp. For example, if you write code that's supposed to run on an 8-bit computer (something embedded) as well as your 64-bit desktop, it makes no sense to limit yourself. For example, say that you know that your number will be between 1-200, you could use uint8_t. But why not use int? It will be the native width of the platform, and likely to be faster. Calculations on an 8-bit int can be slower than 64-bit ints on your 64-bit CPU, because the CPU might have to mask out the relevant part of the register to only operate on your 8 bits. And you don't gain anything by writing uint8_t, you still need to occupy a register on your CPU (which will be 64-bit). The behavior of your program will be the same on both platforms.
4 comments

In that situation you could use uint_fast8_t which is the fastest uint of at least 8 bits.
In practice, how much of my code is going to be run on an 8-bit CPU? Zero. I'd rather have the clarity and consistent behavior of explicitly typed ints than pre-optimize for something that will almost certainly never happen.
There were so many bad programmers who assumed 32 bit machines would last forever, that now we're stuck with compilers that don't default to 64 bit ints even building for 64 bit targets.
This will bite you if your code depends on int being 32 bit (for example if you depend on overflows or use asm). If your code explicitly uses an int32, this will always be true.

Silently increasing the size of an int is more likely to break things than it'll be helpful. If you really want an int to be 32 bit on a 32 bit machine and 64 bit on a 64 bit machine, make it explicit (e.g. intptr_t for pointers)

I don't see how explicit int sizes makes this any worse...
The C8051 architecture is still very much a thing in the MCU world. (As is Atmel AVR.)
I have yet to use a C compiler for an 8-bit platform where int was the native size. sizeof (int) should be at least two chars. Using int instead of an uint8_t where you know its values to fall within those limits would be detrimental to performance in such cases.

That said, the code bases that target both 64- and 8-bit architectures probably aren't that many and both our points are insignificant in those other 99.9% of cases.

The standard requires at least 16 bits in a short and 32 in a long. Oddly "all numeric types are 96 bits" would be fine.
I think it has more to do with memory use. See for instance the "65535 interfaces ought to be enough" thread. If you allocate a bazillion of a certain structure, then using the shortest allocation unit for its fields can make a difference, especially if you have a lot of these "small" fields.