130 points · by Procedural · 10y ago · 101 comments
I've commonly needed access to fixed size numerics, like when sending texture formats to the GPU, defining struct layout in file formats and network protocols, but I have never once thought: "You know what, I'd like to make a decision as to the width of an integer every time I declare a function."
"Just has to work" low level code was the norm during the 16-bit to 32-bit transition, so it was a fucking pain. Notice how smooth the 32-bit to 64-bit transition went? (and yes, it was smooth.) I credit that to high-level languages that don't care about this stuff, and people using better practices like generic word-sized ints and size_t's in lower level code. Keep that stuff on the borders of the application.
I've noticed a decent-sized emphasis on type size in both Crystal and Swift, two not-entirely braindead newer languages. I don't get it, it's a big step backward.
For those who don't know, C's char, short, int and long data types aren't really "fixed size". The standard defines their order: sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long), but the actual size of these integer types depends on the platform and compiler. If you want to use fixed size ints, you'd need to use the uint8_t, uint16_t, uint32_t types from stdint.h. Although interestingly enough C99 doesn't require the platform to provide these types, it only mandates the uint_least_n_t and uint_fast_n_t types (n=8,16,32..) which are guaranteed to be at least, but not necessarily exactly the requested width.
Now you may be thinking "sure the standard says they could be different, but they aren't really, a char is 8bit, a short is 16-bit an int is 32-bit a long is 64-bit". So here's a couple examples for you: many DSP platforms have a C compiler where char is 16-bit. Also Microsoft Visual c++ on windows on x86_64 compiles longs as 32-bit while GCC on Linux on x86_64 compiles longs as 64-bits.
>Notice how smooth the 32-bit to 64-bit transition went? (and yes, it was smooth.)
I know you said it was smooth, and maybe it was for some applications. But for many others, the 32-bit to 64-bit transition actually caused a lot of problems! Andrey Karpov has already done a great job of categorizing many of them, so I won't waste my time repeating him, but you can read his list here: http://www.viva64.com/en/a/0065/
Use the platform-native types (whatever size they may be) unless you have a reason not to, then use <stdint.h> or an analogue. If CHAR_BIT is 13, let char be 13 bits: the platform probably chose that for a reason. When you have to pack it into a TCP header, do your strict fixed-width stuff there.
For data structure fields, especially structs used many, many times like in very large arrays, I'd say it's sometimes worth using fixed size types to get better control over memory use. Using a 64-bit int for a field a 16-bit integer can handle will use up 4x as much memory. And if you've got a ten or a hundred million structs of that type, then it really adds up.
For example size_t is 64-bit on my x86_64 system. But modern x86_64 systems can only use 48-bit address spaces, so a 64-bit sized object can't even be addressed! Even worse is my cpu and motherboard have a 32gb maximum of RAM (for an effective 35-bit physical addressing limitation). And size_t is supposed to be able to store the size of any object in memory, but on this platform it stores things that won't fit in memory. So most of these 64-bits are wasted on modern systems. For files you can use off_t if you're on POSIX, but the C standard doesn't say anything about requiring size_t to be able to store any filesize in a filesystem.
Just using size_t is not enough to make your code work correctly on 64-bit size quantities either. For example, you make your strlen implementation return size_t, and you use size_t everywhere you do anything with a string. But can your application really handle strings that are bigger than the system RAM , or the hardware address space? Are your algorithms even efficient enough to handle the 4,294,967,295 byte maximum string size for a 32-bit system?
The effort to get your program to work efficiently on >32-bit quanities is often much harder than just using size_t instead of int.
So to me, when I see 64-bit size_ts being used everywhere in code that won't actually be able to handle working with >32-bit quantities, it just feels a little useless. Of course this is really more a complaint about how big size_t is on the x86_64 platform than it is a complaint about the idea of size_t in general. If only we had 48-bit size_ts (24-bit would be handy too!)
And the other way around: If you specify int8_t, but your program runs on a 64-bit platform which only can address memory in 64 bit chunks, then you might waste 32-bits of memory for this variable, and addressing it can be slower since the program has to find the 8 interesting bits in a 64-bit register, and discard the rest of the bits so they don't affect calculations.
The only reason to use specific sizes IMO is if you work with loads of data and need to pack it efficiently, or work with bit-specified protocols like TCP packets or files. If you need _at least_ 16 bit of data for example, then you can use the int_least_16_t, which may be 64-bit or 16-bit depending on the architecture.
I believe the parent was positing that the relative sizes you desribe are better than fixed sizes, and as a systems programmer I'm inclined to agree.
Turns out the ATmega328P has only 8bit registers and the ALU operates on 8bit values. We were using 32-bit datatypes in the conditions, which the ATmega328P loaded and compared byte per byte, each comparison (incl. jump etc) cost us something like 16 cycles.
So yeah, the size of the datatypes definitely mattered for us :)
edit: as an addition, we needed quite a while to figure out (and were quite surprised when we did) that ints are 16bit and longs 32bit on this platform/compiler. i guess this comes down to the general question of explicit vs implicit, and i usually do prefer the former.
>> typedef unsigned char uint8;
And then I use uint8 by default (loop counter, accumulator, constant, etc.), unless a larger size number is required.
> Notice how smooth the 32-bit to 64-bit transition went?
There are many reasons for that. For most PC work, a 32-bit int is more than large enough. Going to 64-bit should not have affected that at all. When you're working with embedded systems, you're often working at sizes that are the bare minimum that you can live with. You might also get to work on architectures where char, short, and int are all 32-bit wide. Assume something, and the communications protocol stops working. Moreover, the PC architecture itself supported coexistence of 32-bit and 64-bit executables.
I've deleted a defensive technical response to point out that these dismissive assumptions (usually unjustified) are pretty prevalent on HN, and I don't think it promotes level-headed discussion. It reads like "Let me discredit a stranger's background that I don't know, and then argue my opposing view." It creates a defensive mindset off the bat.
Edit: I mean, your points are valid. We won't agree on them, but I don't like the assumption that we won't agree because I'm ignorant to them.
You have an int16_t? How do you port it to a machine without a 16-bit type? What would happen if you replaced it with a 32-bit type? If you are relying on wraparound, then your code is already undefined, so some compiler is likely going to mess with you anyway.
The stuff about communicating with the outside world is quite different. At this point you have protocols, and it depends on how a protocol is written, and how you are able to actually interact with the world to fulfil that protocol. If the protocol is an ABI, then generally you are fine, because the compiler too will match the ABI. If it is a file format, then you need to know how your file io functions work (do they just write the bottom 8-bits of a char, or do they blat the whole thing across?).
The problem is made more severe when you use "int" and let the compiler decide the size of the variable. I guess I don't know what you're advocating.
> The stuff about communicating with the outside world is quite different.
I meant communicating as a throwaway example. It's a valid example, but really, everything gets affected. For example, a CAN identifier is 29 bits. What generic "int" would you use when you want to fill in this identifier? And no, I work at a level that's lower than an ABI. So, no OS, no file IO, etc.
Hint: you're being done a favor by being forced to think about that.
However the smaller they are the less complex the system is. And running higher level languages is not as taboo today
I also suspect the influence of languages with fanboys, as Rust. I had a 'fight' with these, they really didn't grasp the concept of having a type defined as the natural type of the platform and as having at least (and possibly at most) N bits. I gave up. As long as they have fun with their thing and do not try to spread "the good word" and influence other languages, that would be fine.
Let's hope we won't see the influence of languages whose designers had a gripe against unsigned integers...
That 32 to 64 bit transition? Windows couldn't change the size of "long" because it would break too much windows software that assumed long was 4 bytes. Thus "long long".
The Linux ecosystem fared a bit better because of the greater variety of Unix systems and cross-platform C that ran on them. It was a time of fragmentation and incompatibility, but also a time of posix and attempting to define minimal standards in a portable and flexible way. Windows of course didn't have to care about any of that.
I actually fixed some old-ish classic open source networking software for 64-bit mips, around 2010. You see, it worked OK on x86_64, which is little endian, because in that case the low-order 4 bytes (an ipv4 address) end up in the same place relative to the start address, whether it's a 4-byte or 8-byte type. But for big-endian 64-bit mips, that doesn't work out, the low-order 4 bytes are on the unlucky end of the 8-byte type.
There's also the awkwardly named "ntohl()" and "htonl()" standard library functions that were named in the distant past when it was assumed a long would always be 4 bytes. As soon as that wasn't true they changed to work with uint32_t, as they always should have.
Sure, I'll use a plain int whenever I'm returning a status or error code, and whenever iterating over some trivial range. I'll use a "char[]" or similar for a string of ascii. But for many things, like "count of bytes transferred", or "seconds until timeout", or any meaningful quantity value or anything stored in a struct (meaningful and non-transient), I'll pick the appropriate bit-size, to make the code clear. It's good style because you have to know the limits of the type whenever you do anything non-trivial with it.
These days, there's always a value here or there where 4 billion will sometimes not be enough: bytes, microseconds. I need 64 bits. I could write "long long", but why not write what I really mean: "uint64_t" aka give me 64 bits.
(also, "unsigned" is longer to write and read :)
I credit most of that to Microsoft and the insane efforts they make to support backward compatibility.
They made an extremely complex abstraction layer to run 32 bits applications on 64 bits OS, yet it works very well.
To this day, it's possible to run lot of applications that were written 15 years ago, seamlessly, as they were built and distributed 15 years ago.
https://github.com/tpn/pdfs/blob/master/A%20History%20of%20M...
It was a little weird. I don't know whether it's good or bad overall, but there was definitely a reason for it, the need was clear. Suddenly you didn't know how big an int was, and that matters a lot when you're sending ints over the network and stuffing ints into save games, and it matters a lot when you use an int expecting 64 bits, but you're still compiling code for a Wii and only get 32. It matters for multiply overflows and negative numbers and bit flags and for a bunch of things besides deciding how high your for loop will go or what your largest return value is.
As you say, very few people want to decide what size to use when declaring functions. But everyone wants to know exactly what to expect. If you do declare something and don't actually know what size it is, you have a real problem that can and will lead to crashes.
> Notice how smooth the 32-bit to 64-bit transition went?
I'm not certain, but is it possible it went smooth because everyone working in C/C++ started paying attention to their data sizes?
As a user of Ruby/JS/Python, it would be worth checking what happened to the source code for the interpreters of those languages. When you program in them, yes, you're buffered from a lot of data size issues, but the internals of the languages themselves may be just as fixed-size centric as anything.
We don't have to guess. A huge amount of the code that made this transition was strewn across the internet in CVS and SVN repos, and now in preserved git history. From compilers and libcs to kernels to linkers, loaders and interpreters. They make concessions where they had to (check out glibc), but stay with traditional K&R-style types when possible. The "i32 calculate_age()" thing is way newer than that.
As for fixed size types, what are the alternatives? If you wanted a dynamically sized int, you'd either need to reserve all the possible space you'd need (in which case why not just use a int64_t), or you'd need some kind of heap-allocated integer that can resize itself. We can't hide the fact that the machine itself uses fixed-size ints, unless we are willing to live with a leaky abstraction.
I find that I do want to know the sizes of things fairly often.
The fact that it's possible does not imply that it's a good idea. Some of the macros here are in common use (e.g., countof, although often with other names); some will make experienced C developers say "what's this? Oh, you mean <insert expansion here>; why did you use a weird macro?"; and some, like the redefinitions of case and default are actively hostile and are guaranteed to result in bugs when exposed to experienced C developers.
For more of the same, see "things to commit just before leaving your job": https://gist.github.com/aras-p/6224951
int adress adress adress foo;
vs int * * * foo;
Double pointers are extremely common and triple pointers show up now and then.Also '__attribute__ cleanup' as far as I know only works with automatic variables that live on the stack. Mucking about with code execution and automatic variables as the stack unwinds is not a style I would like to see in general purpose C coding. Its the one type of automatic memory management that you get for free and can't really screw up.
The rest of the macro loops and so forth seem fairly standard. Its good to experiment and explore what you can do with the compiler and the preprocessor.
int double_address foo; /* ? */
Or is it n steps away from ProducerObserverFactoryStragedy?To get the address of an object you use the unary 'address of' operator '&'.
His macro was #define address *
The * is a pointer. You can declare a variable of type pointer to T with as many indirections as you want. int * * * * * * foo is fine. But you also use it to deference your object. bob = * foo;
You can't practically have a different name for each level of indirection to what ever the IS0 standard/Compiler limit is for * .
Also you end up with nasty indirections like this.
**(*((struct foo*)(*bob.x))).y
Its nasty enough as it is without trying to name each pointer indirection. fn main() {
println!("hello, world");
}
I kid, I kid. This looks cool!The cleanup attribute runs a function when the variable goes out of scope. This attribute can only be applied to auto function scope variables; it may not be applied to parameters or variables with static storage duration. The function must take one parameter, a pointer to a type compatible with the variable. The return value of the function (if any) is ignored.
https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attribute...
Also, the for-loop overrides are ugly and pointless, IMO.
Seriously, I'd hope in 2100 we'd have pushed our systems languages beyond facile keyword redefinition. Maybe even towards concurrency and an actor model. Like I explored in my unfinished (sorry, shit happened) book "Scalable C".
Or, Rust.
In fairness however the short POD type names are purely cosmetic.
I've been using them in all my new C code, since I'm stuck to clang anyway, and it's awesome.
[https://en.wikipedia.org/wiki/C_alternative_tokens]
...and no, they're not a good idea, its just a syntactic change. If you want a 'better-C', language-wise, Rust is pretty much best current hope, tho that wont mature for another decade or so.
Thoughts?
The best thing is, though, since Rust is such a young language, you can change it! Imagine trying to add a new language feature to C, something like the ? operator currently being evaluated for addition in Rust. It would take years, if not decades, to get those things in C. Even now MSVC is just rolling out support for C99.
I can definitely see Rust taking over C's current place in the market over the next decade or two. Better memory safety, higher-level constructs to improve productivity, more cross-platform compatibility, and modern libraries to deal with things like Unicode are a huge draw.
Thanks!
> specific bit manipulation
Rust absolutely lets you work at the bit level, you can shift and mask just like in C. > explicit memory management
It depends on what you mean by "explicit" here. Most Rust code has scope-based memory management, but you can also call malloc/free within an unsafe block.Very cool. I was afraid I would be forced into an FFI type scenario (which Rust apparently has good support for anyway).
Thanks!
Still... I wouldn't introduce it into existing/shared codebase due to risk of confusing everyone, and I will never start my own project in C again.
I use there defer for both gcc/clang, countof(arr) -> ARRAYSIZE(array)
In any case, yeah, going through gcc/clang internals, and through C11 standards gives people some ways to speed-up and clena-up their implementations a bit.
I suspect, though, that new successful languages will have automatic memory management, either GC/reference counting or Rust-type borrow checking. There's no reason for a new language with the lack of safety of C.
On other OSes, it really depends on how Apple, Google and Microsoft do their work of "our way or the highway" regarding pushing their safe alternatives.
That's a blimp, a shitty blimp.
So it's not even touching on the subject of the competition with Rust.