1145 points · by fcambus · 10y ago · 581 comments
The best we can do is write simple, understandable code with as few indirections and as little undocumented magic as possible.
Applies very well to all programming.
I was mostly C developer (80% C, 20% C++) for 4 years in a big project (I was backend developer of ICQ Instant Messenger). It has more than 2M lines of C code. Almost all libraries was written from scratch in C language (since ICQ is very old project, many of essential stuff was written within AOL).
I felt comfortable to write high level code in C.
When I read Nginx source code (it's written in C), I see better code quality than 90% of proprietary commercial software which is written on nice and comfortable high level languages.
Good developer is able to write high quality code in C language with minimum bugs in large scale project. Regardless of how nice and high level and convenient language, bad developer will write c....y code.
You can also check my personal project which is written entirely in C. (I didn't contribute for 1.5 years to my github since I was changed countries of living, jobs etc. I hope I will return to it when my life become stable again).
P.S. To be clear, I think that C++11 is great language. But unlike many C++ developers, I love pure C.
But how is that a useful or replicable result, that will work in the real world for other projects? You're basically saying that everyone just needs to be a top 0.001% C programmer. This is the "abstinence-only sex education" of programming advice. It's super simple to not get STDs or have out-of-wedlock pregnancies - just don't have sex with anyone but your spouse, and ensure they do the same. It's 100% guaranteed to work, and if you don't follow that advice you're stupid and deserve whatever bad things happen to you.
A more constructive/charitable phrasing of the parent's point might be: you should only be allowed to code in C if you're already a top 0.001% programmer. Then, obviously, all C code will be good—not that there'll be much of it.
That's actually a more interesting point than it seems. Programmers generally tend to reject the idea of guilds and "professional" licensing—mostly because, AFAIK, most programs aren't critical and most crashes don't matter. But what if, instead of licensing all programming, we just licensed only low-level programming? What if, as a rule, everyone who was going to be hired to write code in a language with pointers was union-mandated to be certified as knowing how to safely fiddle with pointers? That could probably split on interesting dimensions, like a bunch of regular coders working in e.g. a Rust codebase, with a certified Low Level Programmer needing to "sign off on" any commit that contained unsafe{} code, where the actual failure of the unsafe{} code would get the Low Level Programmer disbarred.
I imagine that this poster and his team took a similar approach with C: avoiding the dangerous features, or just finding ways to factor them out.
What is this, 1953?
There are a great number of couples choosing to have children in stable, committed - yet unmarried - relationships.
For the record, I don't think your stupid if you have a child accidentally.
However, once you do accidentally have a child, the results are often not pretty, and I will feel bad watching as you deal with the consequences of your poorly thought out decision.
Regarding programming, I can't see the relationship you make at all.
If you write a good program, well good job. If you write a bad program, you are probably going to write a better one next time. (Ever look back at your old code?)
It takes practice to get good, and the more we work at it, the better we'll get. Just keep trying.
The people and the culture/organization of the shop counts for much more than your language. Language counts for something, but it's not where you get the most bang for your buck, and it shouldn't be your first priority!
That said you can create message-passing systems in either - Objective-C was originally a C library and cross-compiler.
* You've never deployed one.
* You've never had to maintain one.
* You wrote the last line of code and handed it over to the maintenance team, who then never gave you feedback.
* You have no customers.
* You have done a never-before-seen formal analysis of a large scale project down to the individual source line level, and made no mistakes with the formal specification.
The author is correct: use C only if you must. There are still an enormous number of reasons why you must use C, but it should be a constraint imposed on you, and not a language you actively want to start a project in.
Parent seems to believe in nginx. But as a guy who actually tried to do a few of those things with nginx I can confirm that nginx's code base is pretty awful and working around all the usual pitfalls of C in nginx is a huge PITA and enormous amount of work.
(same username on github)
It's the same as with, say, goto or #ifdef's - one has to consider the alternatives and make an informed choice. Most of the time, the alternatives are preferable, but sometimes there either aren't any alternatives, or they are even worse.
Which is not to say that C can't be a whole lot of fun. I love it dearly. But I, too, tend to avoid it when I can. It's just too easy to shoot yourself in the foot.
1. Almost devoid of any documentation. 2. No ADTs - all struct fields are directly accessed, even though there are sometimes very complicated invariants that must be preserved (and these invariants are not documented anywhere, of course). 3. Ultra-short variable names that really describe nothing but their types (it's like Hungarian notation with only the notation part). 4. These mystery variables are all defined in the top of the function of course, making them hard to trace. Does anyone even compile Nginx with C89? 5. Configuration parsing creates a lengthy boilerplate that's really hard to track. 6. Asynchronous code is very hard to track, with a myriad of phase-specific meaning for return codes, callbacks and other stuff that makes reading Boost.ASIO code look like a walk in the park.
I think it really shows the sad state of C programming. Die-hard C programmers always complain C++ is hard to read because of its template and OOP abstractions, and it sometimes really is a mess to read, but C is even harder since large programs always re-implement their own half-assed version of OOP and template-macros inside.
You meant "one of the worst"?
- Was your code unit-tested?
- Did you use the 'strn' functions? (strncpy, instead of strcpy for example)
- Did your code run under Valgrind? (was there valgrind at that time? I'm not sure)
- Was it tested for memory leaks?
- Was there input fuzzying tests?
I agree that there are ways of writing great C code (like nginx, the linux and BSD kernels, etc)
But from a certain point on you're just wasting developer time when you would have a better solution in Java/Python/Ruby, etc with much less developer time and much less chance of bugs and security issues.
https://randomascii.wordpress.com/2013/04/03/stop-using-strn...
There was not one unit test. And there probably still isn't.
Good developer is able to write high quality code in C...
the sufficently smart developer is as much elusive as the sufficently smart compilerEvery professional security researcher reading this just raised an eyebrow and thought to themselves, "That's a vulnerable application." In fact, your team (or a similar one at AOL) did introduce vulnerabilities[1][2]. If we assume that, as you imply, AOL really was exclusively composed of above average C developers writing high quality code, this should really just demonstrate the point for us.
I'm sure your team wrote high quality C code (or at the very least, tried very hard to write high quality C code), and as someone who likes C I also dislike the meme that C should simply not be written, no exceptions. I'd probably change it to, "Don't write C unless you need extreme performance, have great engineering resources and you'll generate unmitigated financial returns such to make any reasonable business risk assessment moot." That means virtually the same thing for anyone reading it, but it sounds a lot less sexy and memorable as far as programming aphorisms go.
I have never professionally audited a C project and not found a vulnerability. Most of my friends in this industry would likely say the same. I've never seen a serious audit of a "large" (100kloc or more) C project by a serious, reputable firm with no vulnerabilities reported. If you wrote 2 million lines of C code, if you wrote libraries from scratch, you have serious vulnerabilities. Otherwise, your engineering practices and resources exceed NASA's in formal verification and correctness.
I believe it is theoretically possible to write 100% safe C code, for some approximation of that ideal that leaves aside the ivory tower definition ("the only safe machine is the one which is off"). But I also believe this is so expensive and resource intensive (secure coding standards, audits, attempts at formal verification and provable correctness) that it's just generally not realistic in practice.
The reason I am saying all of this is not to attack you or your sense of worth as a C developer. Rather, I'd like you to consider that you simply have no idea how many vulnerabilities exist in ICQ. In fact, I found eight different security reports for ICQ, linked at the bottom. One of the more serious ones allowed arbitrary email retrieval, which I'm willing to bet was introduced because your team liked to develop in-house libraries and decided to do that for POP3.
C is a language which is both very powerful and which requires constant vigilance while coding. It is a language which makes pushing a buffer overflow to production on a Friday at 3 pm very easy. I bet your team was comparatively well-versed in C vulnerabilities for the time, but the very fact that you rolled libraries from scratch tells me you already have a high probability of errors showing up. Rolling a library/framework in-house is basically the first thing security researchers look for in an audit, because the third party ones are (usually) more secure due to their exposure. When you further consider the probability of third party software you did use becoming vulnerable in the future, changing compiler optimizations introducing new vulnerabilities and the sheer size of the SEI CERT Secure Coding Standard itself, you are left with a very dangerous risk profile.
We cannot expect C to be a safe language for general use if you need to have the rigor of one of the best research organizations in the world coupled with the top 0.01% of all C programmers. It just isn't feasible.
[1]: http://www.coresecurity.com/content/bevy-of-new-icq-vulnerab...
[2]: https://www.cvedetails.com/vulnerability-list/vendor_id-123/...
I think the reason why every seasoned security researcher I've met also happens to be a heavy drinker or is damaged in some way is because they're in a war of attrition. You want perfect security but it will never happen. These are ultimately mutating, register-based machines. We will probably never be certain that with a sufficient level abstraction a program can be written which will never execute an invalid instruction or be manipulated to reveal hidden information.
Where the theory hits the road is where the action happens.
Which is how we end up with this wide spectrum of acceptable tolerances to security. Holistic verification of systems is extremely costly but necessary where human lives matter. However if someone finds a weird side-channel attack in a bitmap parsing library I think we can be more forgiving.
The whole idea that C programs are insecure by default and can never be secure is where theory wants to ignore the harsh realities. We can write languages with tighter constraints on the verification of the programs they create which will lower the risk of most security exploits by huge margins... but we have to trade something away for the benefit. The immediate costs being run-time performance or qualitative things like maintainability.
What I ultimately think will make these poor security researchers feel better is liability. Having a real system and standard in place for professional practices will at least let us soak up the damage will force us to consider security and scrutinize our code.
This is the wrong mindset and has been the guiding principle behind over a generation of poor programming discipline.
You might be able to rationalize that you don't always need extreme performance, but it's not about performance, it's about efficiency. Efficiency always matters. We live on a small planet with finite resources. Today, the majority of computing is happening with handheld portable devices with tiny batteries. Every wasted byte and CPU cycle costs power, runtime, and usability.
Even if you're coding for a desktop PC or a server application - every bit of waste costs electricity, generates heat, increases cooling load. Every bit of waste costs the user real money, even if they don't see the time that you wasted for them.
Performance is a side-effect. The only thing that matters is efficiency, and it matters all the time.
Most of today's programming problems come down to laziness and fear of "premature optimization" (which is obviously bunk). It is possible to write perfect C code that runs correctly the first time and every time. You do that by planning ahead. Formal specs are part of this.
The same consideration applies to writing, in general. I witnessed this first hand, when I worked at the computer labs at the University of Michigan back in the 1980s. When all anyone had was an electric typewriter, they planned their papers out well in advance - detailed outlines, with logically designed introductions and conclusions. This was a requirement, because once you got into actually typing, correcting a mistake could be expensive or impossible without starting over from scratch.
When we only had Wordstar available, and users came in with the inevitable questions and requests for help, you would still see well-organized papers written with a clear logical flow.
In 1985 with the advent of the Macintosh and MacWrite, all of that changed: People discovered that they could edit at will, copy and paste and move text around on the fly. And so they did - throwing planning out the window. And the quality of papers we saw at the help desk plummeted. Surveys from those years confirmed it too - paradoxically, the writing scores in the better-funded departments dropped rapidly, commensurate with their rate of introduction of Macs.
Planning ahead, making sure you know what you need to write, before you start writing any actual lines of code, prevents most problems from ever happening. It's a pretty simple discipline, but one that's lost on most people today.
> Every professional security researcher reading this just raised an eyebrow and thought to themselves, "That's a vulnerable application."
That may be true, but substitute "C" with "Python" and wouldn't you have the same reaction? Maybe you would expect it to be slightly less vulnerable, but the key risk that I read in that statement (I am not a security professional) is the "2M" and the "written from scratch". The risk from "C" is secondary.
Just out of interest: How many C projects have you audited? And have you ever looked for a relationship between the number of vulnerabilities and the percentage code coverage from automated tests?
A good programmer will make COBOL look clean and understandable. But on average, I could way C code requires a lot more discipline, knowledge, and experience to produce quality code.
I wanted to interpret it as you shouldn't write code if you can avoid it.
I'm certain that's not what he meant, but it sounds better.
I interpreted that differently than you. I didn't think take it to use another language. But to keep c code as concise as possible and to not reinvent the wheel when a good library is available.
I like tweaking younger engineers with C eccentricities, but any commercial code tends towards being as vanilla as possible with lots of error checking and docs to be as clear as possible.
I have seen the quite a few of those and I imagine you wouldn't enjoy to audite their code.
None of which removes the need to write simple, understandable code without undocumented magic. But we should not be throwing up our hands and treating invalid accesses, memory safety failures, buffer overflows, SQL injection, XSS, or a whole host of common failures as inevitable. It really is possible to do a lot better than most programs and a lot better than C.
I used to work in a facility where they'd test systems for radiation hardness. Get the system running, then shoot a proton beam travelling a significant fraction of the speed of light directly at the processor. It doesn't matter if the code was proven correct Dijkstra, it will eventually manifest bugs under these conditions.
[1] practically we resort to empirical testing to confirm that hardware conforms to its spec. But as your sibling says, that's no excuse not to do better in the places where we can.
... and then someone finds a bug in the specification which is provably correctly implemented.
Using gets() to read the input can be provably correct. All you have to do is remove any requirements for security from the program's specification, and specify that the program will always be used in circumstances when the expected input datum will be less than a certain length.
... and then the hardware is buggy or failing. That RAM bit flips and you're screwed. The machine as a whole isn't provably correct.
As a programmer, if the specification is wrong, it's Not My Fault (tm). If you want me to write specifications, well, pay me to do it! I guarantee dramatically better results than the usual crap.
> The machine as a whole isn't provably correct.
As a programmer, defects in the machine are Not My Problem (tm). In any case, hardware vendors have a much better track record than software developers at delivering products that meet strict quality standards.
Provable correctness "...has not been tried and found wanting; it has been found difficult and not tried."
How many modern programmers hold this mistaken belief? It's false -- the Turing Halting problem (https://en.wikipedia.org/wiki/Halting_problem) demonstrates that one cannot establish that a non-trivial program is "provably correct."
It seems the OP got carried away with his rhetoric, and the way he put it is simply wrong.
The halting problem says that there exist programs that cannot be proven correct; it says that for any property you want to prove computationally, no program can give you an answer for every last program. It doesn't say anything about "non-trivial" programs. In particular, if you write programs with awareness of the halting problem in mind, you can write extremely complicated programs that are provably correct.
One straightforward way to do this is with a language that always halts. The proof assistant Coq is based on such a language, and it's powerful enough to write a C compiler: http://compcert.inria.fr/
It is certainly correct that you can't stuff an arbitrarily vexatious program through a proof assistant and get anything useful on the other side. But nobody is interested in proving things about arbitrarily vexatious programs; they're interested in proving things about programs that cooperate with the proof process. If your program doesn't want to cooperate, you don't need an exact answer; you might as well just say "No, I don't care, I'm not trusting you."
Obviously, the solution is to stop writing arbitrary programs. As Dijkstra said long ago, we need to find a class of intellectually manageable programs - programs that lend themselves to being analyzed and understood. Intuitively, this is exactly what programmers demand when they ask for “simplicity”. The problem is that most programmers' view of “simplicity” is distorted by their preference for operational reasoning, eschewing more effective and efficient methods for reasoning about programs at scale.
http://research.microsoft.com/apps/mobile/news.aspx?post=/en...
Also, Knuth in TAoCP spends significant time proving his programs correct.
Further, there is a compiler that is asserted to be proven correct: http://compcert.inria.fr/
Now it is possible you are working with a different definition of "proved correct" than I am thinking.
Of course this is a disadvantage if you don't have sufficient experience in the problem domain. Sometimes I resort to writing prototypes in a script language in that case, translating the best design to the low-level language.
While that certainly can't be a bad thing, you just have to keep in mind that it forces you to think about a specific set of details – the ones that matter for the machine ("how many bytes will the binary representation of this username require") – and it may fool you into forgetting to think about higher-level concerns ("Does å compare equally to å?").
The same code would be much simpler with C++ templates, but the "C being simple" really translates into limited, then you have that some have who never learned how to use macros and this unfounded and misunderstood fear of goto that gives you a nice long lines of error checking, each that that are duplicated if statements character by character where a goto and a single error handler would have worked.
Perhaps this is an exception, but low-level in my case did not correspond to simple code.
Avoiding unnecessary abstractions is important but at the same time those abstractions were invented for a reason. Basically the Go vs generics debate, except even more rudimentary. It's fine if your code doesn't need those abstractions, it sucks badly if it does (eg. gobject)
Algol, PL/I, Mesa, Cedar, Modula-2 and many other languages of similar age or older than C, do offer both higher and lower level mechanisms.
Although developers skipping return value checks is true in most languages.
The tradeoff is that the task at hand tends to have more implementation details in it than in higher level languages, but as you said, this isn't always bad.
> The first rule of C is don't write C if you can avoid it.
Man, this is just lame. C is a really nice, useful language, especially if you learn the internals. It requires discipline and care to use effectively, but it can be done right. The problem is that a lot of C programmers only know C and can't apply higher level concepts or abstractions to it because they've never learned anything else. This makes their code harder to maintain and easier to break.
C is riddled with opportunities to do _just that_ with even the slightest mistake.
Yes, I can make a logic error in any of the above languages that performs some operation a user shouldn't actually be allowed to perform. But I can't accidentally let the user read or write arbitrary memory locations.
With the exception of unsafe blocks or similar mechanisms; being limited to these explicit scopes, most programmer's natural laziness leads to avoiding unsafe behavior whenever possible. It also greatly limits the scope of potential bugs, as well as testing and code review required.
Many of the languages you mention contain an 'eval' method, and most use environment variables in less than transparent ways. I wouldn't be so sure of this claim.
- Using fixed width integers in for loops seems like a fabulous way to reduce the portability of code
- the statements in "C allows static initialization of stack-allocated arrays" are _not_ equivalent, one is a bitwise zeroing while the other is arithmetic initialization. On some machines changing these statements blindly will cause a different bit pattern to end up in memory (because there are no requirements on the machine's representations for e.g. integers or NULL or ..). There are sound reasons why the bitwise approach could be preferred, for example, because a project has debug wrappers for memset that clearly demarcate uninitialized data
- the statements in "C99 allows variable length array initializsers" aren't even slightly equivalent. His suggestion uses automatic storage (and subsequently a stack overflow triggered by user input -- aka. a security bug)
- "There is no performance penalty for getting zero'd memory" this is bullshit. calloc() might optimize for the case where it is allocating from a page the OS has just supplied but I doubt any implementation ever bothered to do this, since it relies on the host OS to always zero new pages
- "If a function accepts arbitrary input data and a length to process, don't restrict the type of the parameter." the former version is in every way more self-documenting and consistent with the apparent function of the procedure than his use of void. It also runs counter to a rule from slightly more conservative times: avoid void at all costs, since it automatically silences all casting warnings.
Modern C provides a bunch of new things that make typing safer but none of those techniques are mentioned here. For example word-sized structs combined with struct literals can eliminate whole classes of historical bugs.
On the fixed width integers thing, the size of 'int', 'long' and 'long long' are designed to vary according to the machine in use. On some fancy Intel box perhaps there is no cost to using a 64bit type all the time, but on a microcontroller you've just caused the compiler to inject a software arithmetic implementation into your binary (and your code is running 100x slower too). He doesn't even mention types like intfast_t designed for this case, despite explicitly indicating "don't write C if you have to", which in 2016 pretty commonly means you're targeting such a device
Regarding calloc (which indeed might be slower than malloc contrary to TFA) - a variable that should have been initialized to something but instead keeps zero bits written by calloc is not necessarily a great situation. If you use malloc, at least Valgrind will show you where you use the uninitialized variable. With calloc it won't, though it might still be a bug - a consistently behaving bug, but a bug nonetheless. Someone preferring consistently behaving bugs to inconsistently behaving bugs in production code might use a function my_malloc (not my_calloc...) which in a release build calls calloc, but in debug builds it calls malloc (and perhaps detects whether it runs under Valgrind and if not, initializes the buffer not with zeros, but with deterministic pseudo-random garbage.)
In starvation, malloc+memset "usually" results in a malloc() failure, instead of the process being silently killed by the OOM killer.
Calloc has another benefit: if you calculate size by n * sizeof(kuku) then it will detect integer overflow (this can be very important for security sensitive stuff that deals with untrusted input), if you did the computation before that and passed calloc( size, 1) then this multiplication and check is another few cycles wasted.
I wonder if they could have done a standard library allocation function like calloc that does the multiplication with overflow detection, does not zero out memory and that returns NULL on zero arguments - but that would be too much to ask.
[1] http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man9/...
[2] http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man3/...
Can you explain this? I'm not seeing it.
You should generally know the range of numbers you're seeking to store in an integer variable, if you don't then you're asking for trouble.
I ran into a bug where I was running some Arduino code (16-bit) on an mBed (32-bit). The use of `int` rather than `uint16_t` caused a timeout to become an infinite loop.
I'm pretty sure it would be impossible to have portability issues due to using fixed-width types - I mean their entire point is to ensure portability.
Their point is against portability as they may not exist at all.
in 99% of the cases, except if you are working with network protocols, [u]intN_t is a bad choice
It will, that's guaranteed by the standard. If it's not a standards compliant compiler/runtime/platform, you've got bigger problems.
>> If you are working with arrays, always use size_t if not, use [u]int_leastN_t
Sure, on array indices, size_t is appropriate.
I can't see an advantage in using 'least' as standards dictate that 8/16/32/64 bit types are available.
>> in 99% of the cases, except if you are working with network protocols, [u]intN_t is a bad choice
No, it's the best choice in most cases because it makes the code a little more explicit and easier to understand, and it makes developers think about the range of the data you're using.
You can still range check the natural integer types, just use INT_MAX and suchlike
Either you need the range, in which case you're stuck with a large type, or you don't and can use a smaller one.
I'm not sure where 'oversized' comes into it.
You've written a list of coding practices which assure job security for folks like me, who have to undo these gross portability problems, bugs, and security vulnerabilities these result in.
for (int i = 0; i < 100000; ++i) // most optimal int size used
Is bullshit, always. uint32_t array[10] = {0};
Does not initialise every element to 0 in the way it would seem to. To see the difference contrast the difference you get when you a) remove the initialiser and b) replace the initialiser with {1}.Yes it does, since atleast C99. As for the others:
a) Removing the initializer will leave the values undefined.
b) Using an initializer of { 1 } will initialize the first element to 1 and the rest to 0.
{} initialises all elements to 0.
{0} initialises the first element to 0 and the rest to 0.
The latter form just introduces confusion.
C++ lets you do "uint32_t array[10]={}", which is something C should allow as well, really. But it doesn't.
I think the real issue here is the inconsistency between C standards on details like this. If you can always assume that your code is built with c99 or later, then use all of its features, but in many cases that's not a realistic assumption.
“If there are fewer initializers in a list than there are members of an aggregate, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.”
The problem I've had (and you probably are referring to) is embedded systems that may not properly zero bss. I've also had problems in embedded systems trying to place "array[10] = {0};" into a specific non-bss section (that was really annoying).
In my experience, TFA is good practices generally, but will have problems in corner cases that you run into in deeply embedded systems.
These are wonderful. Concise nuggets of knowledge that you can keep in your head, little warnings of what not to do.
Side note, it's really fun reading this article about modern C given that I'm working on an experimental programming language meant to replace C [1]. Just today I got the Guess Number Game example working, without a dependency on libc [2] (caveat: Linux x86_64 only so far). So, I'm having fun trying to think about how C could be better, reading implementations of various libc functions, and writing my own "standard library".
For example, in my language, there are no `int`, `unsigned char`, `short` types, there are only `i32`, `u8`, `i16`, etc (I shamelessly stole this idea from Rust). This mirrors the article's suggestion to only use int32_t, uint8_t, int16_t, etc. But, since it's a new programming language, we don't have the other types sitting there as a red herring.
While these are not new ideas - Why not use s32 rather than i32 and so on. Makes more sense if you use something like u32 too.
I think it's important when making another language to really question everything you do in it. Why use this operator, or why use this mnemonic for built in types?
i denotes an integral, as opposed to the also-signed float types?
Those are very old ideas.
> You should always use calloc. There is no performance penalty for getting zero'd memory.
But isn't there? This may be true the first time the program requests a new page from the OS, but when your program starts reusing memory there's going to be a performance hit.
I'd very much recommend that advice; use it all the time, remove it only when it proves to be a problem, and then, as always when optimizing, bear in mind that you've chosen to juggle lit sticks of dynamite and prepare accordingly.
[1]: I hypothesize that this is because what "really" comes back from a malloc is basically too impossibly complicated to model by a human. Even calling it "random" isn't correct; it's not random, but what it is is very hard to characterize.
And by zeroing pages, you prevent lazy memory allocation policies which do not allocate the pages until they're read or written for the first time. This can have a significant impact on memory usage, data locality etc.
So I'm quite skeptical that there is no difference between calloc and malloc. Is there more evidences of this somewhere?
E.g. imagine /etc/passwd is read and later on the page it occupied is put back in the free pool. Another process comes along and asks for memory. It gets that page and can now read /etc/passwd .
If you're sitting in a loop calling malloc(), filling it with data, processing it, and calling free(), changing malloc() to calloc() is just wasting cycles.
I guess one can rely on such behavior when writing a platform-specific libc. But in portable code? Yuck.
Thanks.
Heap allocation can easily contain data that have been previously freed in the same process and hence calloc has to perform some extra work to wipe them.
Yes, calloc() is a few ms slower than malloc(), but does it really matter in 99% of the use cases vs being on the safe side of clean data?
If you fail to do that, pre-zeroing might just give you consistent incorrect behavior. It can also inhibit a compiler's ability to detect that you're accessing an uninitialized object. The compiler has no way of knowing whether that zero-initialization was setting it to a meaningful zero value, or just "clearing" it for safety.
Other than that, you're right.
If you believe a millisecond is a short amount of time you're probably not writing video games. At 60 fps, you only have 16.67 milliseconds to render each frame, so wasting a couple of milliseconds would have a huge impact on what you'd be able to do for each frame.
Luckily, calloc doesn't actually take milliseconds unless you're making a very large allocation.
Care should be taken when it really matters, not in every single line of code.
Why would you even be using C if it didn't?
- Exposing OS APIs to other languages
- Integration with an SDK that only provides C APIs
- Improving an algorithm until it runs at the desired speed for the customer (no need to shave every last ms)
- Targeting embedded processors
Although, I personally would rather use either C++ or a safer systems programming language.
efficiency really matters and costs real money.
Of course if you're using dynamic allocation in an embedded system then you have other issues anyway...
Sometimes.
10 million times $.02 is only $200,000.
And the probability of you shipping 10 million units of anything is vanishing small. 10,000 is more typical--at which point the savings is $200. Not having to think saves you more money.
If a developer is doing micro-optimizations without numbers of what it brings in terms of business case, then no.
The first rule of C is to ALWAYS use C
The second rule of C is to NEVER use [u]intN_t, use [u]int_leastN_t instead and (unsigned) char when you want to deal with bytes
The 3rd rule of C is to never use anything else when size_t should be used
The 4th rule of C is that everyone has his own style, so declaring variables on top is totally acceptable (and more clean IMO)
The 5th rule of C is "enjoy your stack overflow" when using VLAs instead of malloc (not to mention that VLAs are optional in C11)
>which also means it's capable of holding the largest memory offset in your program.
wrong
>C99 gives us the power of <stdbool.h> which defines true to 1 and false to 0
I do use it but it is useless
>readability-braces-around-statements — force all if/while/for statement bodies to be enclosed in braces
don't use a shitty editor
>You should always use calloc
good thing calloc has: checks for overflows when multiplying the typesize and the arraylen
bad thing: makes programmers think that it will make your pointers null
>you can wrap it with #define mycalloc(N) calloc(1, N).
but the two arguments is the only good thing calloc has
>growthOptional
I can't see any reason why the second one is considered better
printf("Local number: %" PRIdPTR "\n\n", someIntPtr);
which is quite unreadable to say the least. To address this issue I even wrote a small library (https://github.com/cppformat/cppformat) that allows you to write something like this instead: print("Local number: {}\n\n", someIntPtr);
It is written in C++ rather than C, because the latter doesn't have facilities (at least overloading is necessary) to implement such library.- Option to insert commas or underscores every three digits (for decimal) or four digits (hex/binary/octal).
- Option to print floating in engineering format (make exponent a multiple of 3).
- Option to print floating but with a specific given exponent.
uint32_t numbers[64];
memset(numbers, 0, sizeof(numbers) * 64);
That is certainly true because that is a buffer overrun.[1] https://github.com/btrask/stronglink/blob/master/SUBSTANCE.m...
6.2.5.15 - http://port70.net/~nsz/c/c11/n1570.html#6.2.5p15
6.3.2.3.7 - http://port70.net/~nsz/c/c11/n1570.html#6.3.2.3p7
B.19 - actually I think 7.20.1 is a better demonstration that these are integer types (and not, since it's never mentioned, character types) - http://port70.net/~nsz/c/c11/n1570.html#7.20.1
7.20.1.1.3 - http://port70.net/~nsz/c/c11/n1570.html#7.20.1.1p3
http://port70.net/~nsz/c/c11/n1570.html#6.2.5p4 leaves open the option for extended signed integer types, and the following paragraph provides for an unsigned integer type for each signed type, extended signed types included.
So it would be perfectly possible, if not actually very reasonable - not that this is stopping anybody at the moment - for an implementation to provide __int8, a signed 8-bit integer type that fulfils all the requirements of uint8_t, but is not a character type, and use that as uint8_t. Then, conceivably, it could fail to support the use of uint8_t pointers to alias other objects, something supported by the more usual situation of using unsigned char for uint8_t.
I'm not sure that anybody would do this, but they could. I'm rather surprised gcc doesn't do it, come to think of it, just to teach its users a lesson. Maybe I should file a bug report?
I looked briefly previously and somehow got the sense that extended types could only be larger than standard types, but this time I found that 6.3.1.1 explicitly mentions same width extended types.
Personally, I've been happy with GCC's decisions on such issues.
As for the actual C content, frankly this was where I went to when I was wondering how to write better (modern) C, so I don't really know any better. The writing is almost certainly opinionated and as above, could be a lot more comprehensive.
(oops edit window left open for a while, see sibling!)
make -j doesn't help linking speed, unless multiple binaries are begin built.
The linker invocation is a single make job, which is the unit of make -j parallelism.
It was very challenging! I was learning how to do threading in C for what was one of the most complex assignments in my degree. However, I don't regret a moment of it. Even with a mark that was lower than my average programming assignment marks, I learned more in that assignment than I did in anything else while at uni.
Being forced to RTFM because it wasn't abstracted away for you was exhilarating once I understood what was going on. And man, it was fast! Much faster than others who had programmed in Java.
I wish I had more reasons to write C, because I love it.
>The only acceptable use of char in 2016 is if a pre-existing API requires char (e.g. strncat, printf'ing "%s", ...) or if you're initializing a read-only string (e.g. const char hello = "hello";) because the C type of string literals ("hello") is char .
Heh, basically you need to use 'char ' for strings. I would far prefer if strings were unsigned so that I could use 'uint8_t ', but if you try it you'll get tons of conversion warnings and your code will look weird.
Void pointers do not allow pointer arithmetic (GCC allows it as an extension).
The correct type for pointer math is uintptr_t defined in <stddef.h>.
The casts to uintptr_t are not needed in this case, as the result of subtracting two pointers already yields ptrdiff_t.
Also, the mere subtraction of two pointers that do not point to the same "array object" yields undefined behaviour as per the standard.
In practice it works only if sizeof(ptrdiff_t) == sizeof(uintptr_t) AND the system uses two's complement for signed integers. Neither property is guaranteed by the standard.
I think the correct way to find the byte offset is this:
ptrdiff_t diff = (char*)ptrOld - (char*)ptrNew;I was dreading getting back to C++ with the Rule-of-3 and now the Rule-of-5 -- what a pain! Fortunately I ran into the Rule-of-Zero as described here: http://accu.org/index.php/journals/1896. The CppCoreGuidelines have a more restrictive Rule-of-Zero but allude to the link's form . . . the only way I'll get back to C++ is if I can avoid move-constructor and move-assignment for the majority of my work ... and the link provides the answer!
But I agree, a short guide for C++ with the most important stuff in it would be nice.
We've got these facilities, they're not exactly bleeding edge (the clue's in the name C99), let's use them!
I like using anonymous structs with variable initializers to provide parameters to functions with default values -- nice and clean!
C99 is not your grandparents' C. It has kept up with the times.
A more thorough resource I cannot recommend highly enough: 21st Century C[0]
I would not even dare to use threads without the support of these tools. In fact, this seems a side where C has a big advantage over other languages.
So, you're back to writing C89, in 2016.
For bonus points it shouldd prefix the clang-format command with "exec" but that's not a correctness issue.
Now, if you want to talk about signed overflow, bitwise operations on signed types, wacky undefined behavior, or memory management, that stuff is pretty hard to deal with in C. But 99% of the time when people are shaking their fists at "shitty ol' C ruining the Internet for everyone", they mean buffer overflows, and it just shouldn't be an issue these days.
Consistency means avoiding special cases. Variable length arrays are too prone to special cases - IMO, just don't use them. malloc vs calloc is too prone to special cases, that rule is worthless. The rule "never use memset" is full of special cases, also worthless. (And in fact, for your larger automatic initializations, gcc just generates code to call memset anyway.) I would say "always use memset when you need zeroing - then you'll never be surprised." The fewer special cases you have to keep track of, the better.
"Never cast arguments to printf - oh but for %p, always cast your pointers to (void *)" again, worthless advice with an unacknowledged special case.
The way to write code that always works right is to always use consistent methodology and avoid any mechanism that is rife with special cases.
The advice "always return 'true' or 'false' instead of numeric result codes" is worthless. Functions should always return explicit numeric result codes with explicitly spelled out meanings. enum is nice for this purpose because the code name is preserved in debug builds, saves you time when working inside a debugger. But most of all, it's a waste of time for a function to return a generic false/fail value which then requires you to take some other action to discover the specific failure reason. POSIX errno and Windows GetLastError() are both examples of stupid API design. (Of course, even this rule has an exception - if the function cannot fail, then just make it return void.)
I actually like declaring my variables at the top. To me, this seems more readable than searching for declaration statements throughout the code.
Why should I not do this?
If there's a section of code in your function that may or may not be executed, depending on a conditional, then allocating the memory for variables used within that code block will be a waste if you end up not executing it. Now, you could argue that that block should be turned into a separate function, but now you're doing another function call (unless it gets optimized out) which wastes performance, and you're making the code more cluttered if the code block is relatively small and not really worth turning into a separate function.
It makes the code more readable.
{
int x = 3;
do_something();
int y = 4;
}
you write this: {
int x = 3;
do_something();
{
int y = 4;
}
}
As a Lisp programmer, I prefer clear binding constructs which put the variables in one place. The (define ...) in Scheme that you can put anywhere makes me cringe; you have to walk the code to expand that into proper lambdas before you can analyze it. Other Lisp programmers don't agree with me. The CLISP implementation of Common Lisp, whose core internals are written in C and which historically predates C90, let alone C99, uses a "declarations anywhere" style on top of ANSI C. This is achieved with a text-to-text preprocessor called "varbrace" which basically adds the above braces in all the right places.You get better locality with explicit binding blocks, because their scope can end sooner:
{
foo *ptr = whatever();
/* this is a little capsule of code */
/* scope of ptr ends */
}
{
foo *ptr = whatever_else(); /* different ptr */
/* this is another little capsule of code */
}
These tighter scopes are much more tidy than the somewhat scatter-brained "from here to the end of the function" approach.I can look at that capsule and know that that ptr is meaningful just within those seven lines of code. After the closing brace and before the opening one, any occurrence of the name "ptr" is irrelevant; any such occurrence refers to something else.
https://hg.mozilla.org/mozilla-central/file/tip/mfbt/SizePri...
It's not exactly 100% complete in the literal sense, but everything covering the language spec and usage is there. I highly suggest working through it, as the book itself is incredible for going from beginner to expert in the short span it does.
There is also the fact that you permanently lose one register in your function (ebp) if you use alloca(). This is important on 32-bit x86 but is rarely discussed.
There is essentially no implementation difference between VLAs and alloca().
The "machine dependent" reason is out of date though.
Also, VLAs are optional in C11, and may not be supported in otherwise-near-C99 compilers for small processors. (Of course, alloca() is not standard at all.)
There's no way to recover from any stack allocation.
#define TOO_BIG 1000000
This: {
double big_array[TOO_BIG]; // not a VLA
}
is no safer than this: {
size_t size = TOO_BIG; // size is not a constant
double big_vla[size];
}
If you use VLAs (variable length arrays) in a manner that permits arbitrary unchecked sizes, then yes, they're dangerous. If you carefully check the size so that a VLA is no bigger than a corresponding fixed-size array would have been, they don't introduce any new risk.(I'm not sure why VLAs were made optional in C11, at least for hosted implementations. Support for them was mandatory in C99, and I'm skeptical that they impose any significant burden on compilers.)
Note that the overarching theme of C99 was making C a better language for numerical code (ie competing with Fortran), thus the introduction of VLAs (as well as _Complex, tgmath.h, restrict, and possibly other things I forgot ).
Respect earlier developers and try to minimise _unnecessary_ changes that break version control history. Did earlier developers use names you don't like? Formatting you don't like? InconsistentCamelCasing or other_naming_paradigms you don't like? Let it be -- at least until you do a refactoring where _you_ claim responsibility.
It may not be a good point to uncritically and retroactively apply the good points from the original article in an old code base.
2 bit example:
00 => -1 01 => 0 10 => 1 11 => 2
or: 2 bit example:
00 => -2 01 => -1 10 => 0 11 => 1
This even wrapsaround naturally.
test.c:1:2: error: #import is a GCC extension
This ought to carved into the walls of R&D departments everywhere.
I realize this is a bit of a style question, but I'm curious.
Unlike gcc, clang does not have good documentation for its warning options. The best sources I've found are the clang code itself (https://github.com/llvm-mirror/clang/blob/master/include/cla...) and http://fuckingclangwarnings.com/.
- Add security measures provided by your compiler to your builds: -fstack-protector-strong on GCC. -fsanitize=safestack on Clang if you have a version that's new enough.
- Build the program with AddressSanitizer and run it with typical data. Run it through a fuzzer afterwards.
for (infer x = 0; x != 10; ++x) ...
If the compiler can infer the type, use the fastest integer. If it can not infer, use the largest integer.
I'm sure this would create difficulties with structs, but at least for local integers it would be nice.
This is IMO very close to the inference you describe, while still providing some stipulations about what you need.
int8_fast_t and its siblings are defined in <stdint.h>, described in this article (though it would be nice if the article mentioned them).
Unless you're doing memory-mapped IO, or other very-specific things, you probably only need the _least_t or _fast_t types (int16_least_t, e.g.).
When I hear buffer overflows I think.
Programmer trying to be smarter than he is. Depreciated unsafe string functions. Unnecessary pointer arithmetic. No unit tests Failing to use static code analysis tools
My only concern about buffer overflows in C is that memory error continue to happen in software that I depend upon in my daily life.
Chrome, Firefox, Linux, OpenSSL, all these things suffer memory errors that compromise my security. Anyone doing security work in C in 2016 is in my opinion committing malpractice and putting user's at risk because their ego's can't take not fiddling bits by hand.
> The solution here is to always use an automated code formatter.
Spot on. Python got that part right.
But on the writing side, it's harder (impossible?) to have tools that format an entire file, because without braces, various things could be at different levels of indentation. You have to indent as you go, and changing the level of indentation can be a little painful.
In curly brace languages, you can sometimes work very fast by crapping things onto the page and then formatting the entire file.
I don't know which I absolutely prefer, but there is a tradeoff to whitespace based blocks. That said, I think C & Java suffer for the combination of optional braces and lack of a standard format tool.
Instead use C99 ... which is from 1999. (Yes, I know most people didn't learn it in the 90s)
In practice a lot of c99 got into gcc after 3.0 (2001) and it still took a bit of time for any distribution to include it as stable. If I remember correctly, lots of distributions held on to 2.9x for as long as possible. I'd say realistic c99 support has ~10 years now, rather than 17.
I see this a lot shouldn't O3 produce better optimizations? Is that people have large codebases? OR is it that O3 does some CPU/memory tradeoffs? OR something else?
I usually compile with -O2 and annotate certain functions with O3 - if it looks like vectorization will give the function a boost.
ALSO it generally produces a larger binary which means less of it fits in the cache. I know a while back it was often suggested to try O3 and OS because often OS ended up being faster.
In some ways -Wextra is too much: it's annoying that -Wall with -Wextra complain about unused parameters.
I am not a fan of the use of macros here. You should never use macros.
Instead maybe: static inline void *mycalloc(size_t sz) { return calloc(1, sz); }
lmaoed at that one
> Standard c99
If you have to write C, why not go with ANSI C/C89 for compatibility/portability reasons?If publishers and programmers with popular blogs can't get a consensus on what constitutes correct C, how could I ever hope to produce it?
Case in point https://news.ycombinator.com/item?id=10864601
int is a type that's at least 16 bits large. I can't see the problem with using it. If I specify that I want a type that's 32 bits large, my code won't run on 16 bit systems.
Why should I assume? Because the author doesn't believe in writing code that works on "20 year old systems"?
Yes, the int is technically less portable. No, I don't see any reason to use that longer name.
Why not?
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?
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".
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
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.
`int` is at least 16 bits, `long` is at least 32 bits, `long long` is at least 64 bits, and `size_t` is big enough to hold the size of the largest object you can allocate - and in most cases that is all you need to know.
The exact width types can be useful if you're marshalling data to and from an exact-width format, like a network protocol or file format.
You should know the range of values that you are expecting to be holding in an integer, and choose the type accordingly.
The only advantage to choosing an exactly-N-bit type over an at-least-N-bit type is possibly saving some space in very large allocations. In most cases this won't be important - and when it is, the mininmum-width types from stdint.h (eg int_least32_t) are more apropos than the exact-width types.
The disadvantage is the impedance mis-match with all the existing libraries of code using the basic types.
IMHO, "int" is perfectly acceptable if you just want to use the platform's preferred word size (and are fine with the possibility of it being only 16bit). Also, "char" is perfectly acceptable too if you're dealing with ASCII. This is valid for both the signed and unsigned variants.
The general rule should be using the language types as long as you're not assuming something about their size, only then use "stdint.h" because it makes your assumption more explicit.
Now, nobody uses "short" or "long" to mean "something smaller or shorter than the platform's int", so these are usually something to avoid.
Have a reference to the norm easily accessible and don't use options of the compiler which impact you don't fully know.
Most developer are poorly understanding multithreading and it can be tricky to make a portable library that has this property. Don't hesitate to stipulate in your documentation that you did not cared about it, people can then use languages with GIL (ruby, python ...) to safely overcome this issue.
Modern language are social, take advantage of sociability (nanomsg, swift, extension, #include "whatever_interpreter.h" ....).
Programming in C with dynamic structures is guaranteed to be like a blind man walking in a mine field: you totally have the right either to make C extension to modern language OR include stuff like python.h and use python data structure managed by the garbage collector from C.
Old style pre allocated arrays may not be elegant, but that's how critical system avoid a lot of problems.
DO NOT USE MAGIC NUMBERS...
USE GOTO for resource cleaning on error and make the label of the goto indentend at EXACTLY the same level the goto was written, especially when you have a resources that are coupled (ex: a file and a socket). Coupling should be avoid, but sometimes it cannot. Remember Djikstra is not that smart, he was unable to be a fully pledged physicist that can deal with the real world.
Avoiding the use of global variable is nice, but some are required, don't fall for the academic bias of hiding them to make your code look like it has none.
Copy pasting function is not always stupid (especially if you use only 1 clearly understandable function out of a huge library).
Be critical: some POSIX abstraction like threads seems to be broken by complexity: KISS.
Modern C compiler are less and less deterministic, learn about C undefined behaviour and avoid clang or GNU specific optimisations and CHECK your code gives the same results with at least 2 compilers.
Don't follow advices blindly: there are some C capos out there that dream an ideal world. Code with your past errors in mind and rely on your nightmarish past experiences to guide you to avoid traps. Feeling miserable and incompetent is some time good.
Resources are limited : ALWAYS check the results of resource exhaustion in C instead of relying on systems and always have error messages preallocated and preferably don't i18n them. Don't trust the OS to do stuff for you (closing files, SIGSEV/SEGFAULT ...).
KISS KISS KISS complexity is your enemy in C much more than in other languages. Modern C/C++ want you to build complex architecture on libraries that are often bloated (glibc).
Egyptians are nice looking.
Once you finished coding you have done only the easy part in C: - dependency management is hard in C; - have a simple deterministic build chain; - you should write your man pages too; - you should aim at writing portable code; - static code analysis, maybe fuzzing, getting rid of all warnings is the last important part.
Coding in C is just about 15% of the time required to make great software. You will probably end up debugging it much more than you write it: write code for maintainability as your first priority and do not under any circumstances think that you can handle multiple priorities (memory use, speed, ...).
Above all : just write maintainable code, please. This rule is the golden rule of C and it has not changed.
I would add one thing.
Know your target. Batch programs, daemons, microcontroller programs, cross-platform programs are all different and you're going to end up with different styles.
Well that is the difference between writing code and bringing a solution that fits a problem.
I fully agree.
But IT has become shove sellers to other shove seller hoping for a new gold rush to happen.
Computers have still not proven to be an actual improvement to the economy. Positive impact cannot be measured. I guess I know why.
It looks like the lost bet of Diesel to empower the poorest to have access to the economy and fight equally with capitalists able to buy steam machine thanks to the banks: IP laws makes it impossible for a new economy to rise.
Those who do not learn from the errors of the past are doomed to reproduce them.
Ha ha ha. What kind of programmer would argue this? Do they ignore Windows 64? The type long is 32 bits there.
so defining a string happens how if not:
char *my_string = "Hello";
i meant a variable
char * my_string
It must be a const char * my_string You can still assign a different string to that, as my_string is not const.
For my_string to be const, you'd have to use char * const my_string
Now the location pointed to by my_string is writable but I cannot change the location.
To make it entirely unmodifiable, you'd use const char * const my_string.
On the other hand, it might make more sense to use an array here.
const char my_string[] = "hello";
No thanks; sticking to C90.
> LTO
Violates ISO C, which says that semantic analysis is done in translation phase 7, and only linking takes place translation phase 8.
Link-time optimization is a language extension which alters the concept of a translation unit. In some ways, multiple translation units become one unit (such as: they inline each other's code, or code in one is altered based on the behavior of code in the other). But in other ways they aren't one translation unit (e.g. their file scope static names are still mutually invisible.)
One reason I don't use C99 is that many of its features aren't C++ compatible. Most of C90 is. With just a little effort, a C90 program compiles as C++ and behaves the same way, and no significant features of C90 have to be wholly excluded from use.
Portability to C++ increases the exposure of the program to more compilers, with better safety and better diagnostics.
In some cases, I can use constructs that are specially targetted to C or C++ via macros. Instead of a C cast, I can have convert(type, val) macro which uses the C++ static_cast when compiled as C++, a coerce(type, val) which uses reinterpret_cast, or strip_qual(type, val) which uses const_cast. I get the diagnostics under C++, but the code still targets C. I'm also prevented from converting from void * without a cast, and there are other benefits like detecting duplicate external object names.
This way of programming in C and C++ was dubbed "Clean C" by the Harbison and Steele reference manual.
C90 is a cleaner, smaller language than C99 without extraneous "garbage features" like variable-length arrays that allocate arbitrary amounts of storage on the stack without any way to indicate failure to do so.
The useful library extensions in C99 like snprintf or newer math functions can be used from C90; you can detect them in a configure script like any library.
The overall main reason is that I simply don't have faith in the ISO C process. The last good standard that was put out was C90. After that, I don't agree with the direction it has been taking. Not all of it is bad, but we should go back to C90 and start a better fork, with better people.
git checkout -b c90-fork c90
git cherry-pick ... what is good from c99-branchBut here is the thing: all the initialization comes from the initializer, not from the struct type, and the only default value you get is the good old 0 (0 integer, 0.0 floating point, null pointer). So, if you want any other default, designated initializers are basically useless.
The designers of a data type want to provide initialization mechanisms with defaults which they control from the site of the definition of the type. We can do that in C90 with macros. Macros ensure that everything is initialized. If we add a member that must be initialized with a non-default value everywhere, we add a parameter to the macro, and the compiler will catch all the places where the macro is called with the old number of parameters.
struct foo {
char *name;
int bogosity;
};
#define foo_anon_init(bogosity) { "anon", bogosity }
#define foo_init(name, bogosity) { name, bogosity }
You provide all the variants in one place which do all the forms of defaulting which you need, and which stick the parameters into the correct place, and then just use them everywhere else.Even if you have designed initializers, it's still good idea to wrap initialization that way; they don't replace its benefits.
Suppose I add a frobosity member, and there is no obvious way to default it. All the places where the structure is instantiated have to be analyzed case by case to choose the appropriate value. Designated initializers (alone) won't help; we add the member to the struct and nothing happens. It defaults to zero everywhere it is not explicitly mentioned with a designated or positional initializer. With the macros we just add it as a parameter:
struct foo {
char *name;
int bogosity, frobosity;
};
#define foo_anon_init(bogosity, frobosity) \
{ "anon", bogosity, frobosity }
#define foo_init(name, bogosity, frobosity) \
{ name, bogosity, frobosity }
Now "make -k" and fix all the places where the macros are called with too few arguments, choosing a value for the frobosity.With designated initializers we can of course do:
#define foo_anon_init(bogosity, frobosity) \
{ .name = "anon", .bogosity = bogosity, \
.frobosity = frobosity }
But that brings very little to the table when we've gathered all this stuff in one place (which alone reduces mistakes) and we are initializing every member to a nonzero value.Languages that have keyword initializers are great when the class supplies defaults for all the ones that the constructor doesn't specify.
(make-instance 'foo :frobosity 42) ;; 50 other slots defaulted for us
If you want to change a default, you don't want to go to all the places where the type is instantiated and update the initializer!!!Eek! Not what I was expecting. In the video game world there is a not so small contingent of "write everything in C unless you have a really damn good reason not to".
Great post though. Now go forth into the world and write C, my friends!