4 ms·
I don't write much C, so perhaps someone can educate me. What are the advantages of having data types that behave differently on different platforms, like C do
by michaelt 11y ago
I don't write much C, so perhaps someone can educate me.
What are the advantages of having data types that behave differently on different platforms, like C does? It seems to make code less portable and I'm having difficulty seeing what the benefits are.
I can appreciate that, on an 8-bit processor, you'd want access to an 8-bit data type for speed - but wouldn't that be better accomplished by explicitly choosing an 8 bit data type?
- pmelendez 11y agoI can think in at least one reason. Having let's say `int` as long as the register size would get you portable efficiency since it doesn't matter if the underlying processor is 8, 16 , 32 or 64 bit, you always will have a type that fix just right. There are some other types (i.e int32_t, int64_t, etc) that you could use if you want to be sure that your variable would have the same size regardless of the architecture.
- okasaki 11y agoFor that, there's now intN_fast_t in stdint.h - the fastest data type that's at least N bits.
- brudgers 11y agoUndefined behavior in C standards is often not a result of technical decisions but of practical concerns when developing a consensus during the standards process. The people on the standards committee historically included compiler vendors and users of diverse operating systems. When the process started in 1983, there were 8, 16, and 32 bit systems [and things like Burroughs 48 bit word systems]. The practical decision to leave the sizes undefined was made so that nobody was burdened unfairly. It's choices like this - not biasing stakeholders toward forgoing a standard for clear business reasons - that makes the adoption of standards likely. Subsequent C standards have adopted the same undefined behavior for the same reasons [there are still 8 and 16 bit systems developed with C] and to facilitate backward compatibility of the new standards.
- sjolsen 11y ago>It seems to make code less portable Than what? Than a freshly designed C-like language? Yes. But ISO C wasn't an effort to invent a new language. It was an effort to standardize existing practice, and provide a platform for improving C. One of the core goals of ISO C is to maintain every last bit of backward compatibility possible, which is why integer widths are not precisely specified: had they been, multiple vendors' implementations and the code that was written for them would have broken. But to your main point, I agree: explicitly sized integer types are almost always what you should use. For example, don't store a pointer in an unsigned long (and certainly not a signed long); store it in a uintptr_t, or hell, just store it as a pointer. In fact, the fundamental types like int, long, etc. are effectively just shorthand for int_fast16_t, int_fast32_t, etc., but without the mnemonic value.
- smegel 11y agostdint.h