9 ms·
> If I specify that I want a type that's 32 bits large, my code won't run on 16 bit systems. Why not?
by officialtedleo 11y ago
> If I specify that I want a type that's 32 bits large, my code won't run on 16 bit systems.
Why not?
- ue_ 11y agoNevermind, I'm wrong. I've read that if one uses int64_t with a compiler that targets a 32 bit system, doing various operations on the int64_t variable will be much slower because more machine code instructions need to be generated. The point stands: Why not use int if one is looking to target any architecture that C will run on?
- Gankro 11y agoIf 16 bits is enough, use an explicitly 16-bit integer. If you want something architecture-sized (e.g. because it's dealing with pointers/addresses), use things like `size_t` which makes the intent much more clear, and which are better defined. In most places, if you're using an `int` for non-address-y stuff you're just wasting space on wider archs, or you're overflowing on less wide ones. The only exception off the top of my head is "I have an array of bytes, but want to bulk process more efficiently than u8 would allow". Things like `size_t` (or explicit SIMD types!) are still probably a better choice there, if only to simplify the rule to "just don't use int".
- lmm 11y ago> I've read that if one uses int64_t with a compiler that targets a 32 bit system, doing various operations on the int64_t variable will be much slower because more machine code instructions need to be generated. Yep, but presumably you picked int64_t for a reason. If you want a 32-bit variable, use int32_t. It would be an extremely rare platform on which int16_t is noticeably slower than int. The very minor platform-specific performance improvement you might get from using int rather than int16_t is very rarely worth the risk of introducing an overflow on the few platforms where int is 16 bits[1], and not noticing it because int is longer than that on the platform you develop on. [1] remember that a signed integer overflow is undefined behaviour which should be regarded as equivalent to a security flaw - the compiler is permitted to send all data your program has access to to the mafia if your program contains a signed integer overflow anywhere, and some compilers will
- Triave 11y ago"int" doesn't reveal the intention of the programmer - they might just have used it because it's "int", not because it changes size based on what system you are targeting. If they used 'int_fast16_t' from <stdint.h>, you have at least an idea that they considered that it might only be 16 bits, and that it can be a larger type on systems where operations on 64-bit types are faster.