11 ms·
The Ten Commandments for C Programmers (1987)
- zoomablemind 6y agoI'd supplement the first commandment with "Fear not the -Wall, for it clears thou path to truth". Personal reminder: "Initialize thou variables or endure the torturous trials of doubtful debugging" "Never refuse the helping hand of thou compiler" and "No one seeking a refuge after arduous truth seeking journey in C has been turned away from StackOverflow."
- illuminated 6y agoInstead of the second, I'd rather put: "Thou shalt understand pointers, before using them"
- gigatexal 6y agoCan you program in C effectively without pointers?
- klyrs 6y agoDepends on what you mean by "effectively." If you wanna, say, do an exhaustive search over all 4-dimensional integer vectors in a rectangular region, and print off the ones that satisfy some relationship, you don't need pointers (nevermind what printf and string literals are doing under the hood). It's a wonderfully beefy desktop calculator, in that way. But for most applications, pointers are pretty much necessary.
- WalterBright 6y agoArrays in C (once passed to functions) are pointers, even when they use array syntax: https://www.digitalmars.com/articles/C-biggest-mistake.html https://www.digitalmars.com/articles/C-biggest-mistake.html
- klyrs 6y agoYou don't need arrays for the code I was describing: it's a nested for-loop on 4 ints. But, yeah, that's a really common mistake.
- illuminated 6y agoNope, therefore you cannot do it effectively if you do not understand them :)
- Gibbon1 6y agoYou can program C effectively without pointer arithmetic. Storing copies of pointers for later is usually a bad idea.
- pm215 6y agoThe second item is warning against a particular misuse of pointers that was apparently widespread at the time. On VAX Unix, it happened that the memory at address zero of a process was readable and contained zeroes. So a lot of code would misuse a NULL pointer as being equivalent to a pointer-to-an-empty-string, for instance: worked fine on the VAX!. So it's kind of a specific flavour of commandment 10. These days the common machines don't have a readable address zero, and all the old non-portable code has faded into history.
- asveikau 6y ago16-bit x86 also had the interrupt handler table at linear address 0, I seem to recall some compilers for DOS that would make NULL point at that.
- oriolid 6y agoYes. At least writing to interrupt vector table usually crashed your computer right at the point. I remember a certain DSP architecture that system flags near zero address. It was an interesting experience to debug a program that failed because a write to struct member through null pointer switched the machine to a different instruction set.
- kevin_thibedeau 6y agoEvery MMU-less micro lets you read address 0.
- monocasa 6y agoA lot of micros have MPUs that'll catch address 0 accesses without a full MMU. AFAIK all ARMs newer than ARM7 (ie. ARMv5) have one for instance.
- RealityVoid 6y agoYeah, they will, if you activated it. And if you made access to 0 address be caught explicitly ( you might have the MMU active but not have it configured in such a way)
- ape4 6y agoI get why they are using King James language but a button to translate to modern English would help.
- iso-8859-1 6y agoI, for one, prefer my bibles with interspersed lines of Ancient Greek, so that you can interpret yourself. Our language will never keep changing, but the source remains the same.
- greenyoda 6y agoThe Ten Commandments were originally written in ancient Hebrew. They were passages in the Hebrew Bible, which the Christians later adopted as the Old Testament. It was the New Testament that was originally written in Greek.
- zodiac 6y agoIt's not even correct - "thy arrogance" should be "thine arrogance"
- matvore 6y agowhen thou least expect it. Should be “when thou expectest it least” lest thou tear thy hair Should be “lest thou tearest thine hair” as I seem to recall the h sound acting like vowel for words that sound different based on what follow them. lest grievous harm befall thy program. Should be “befalleth”
- all2 6y agoToo bad you can't "requesteth a pull" to update the language a bit.
- yesenadam 6y agoI believe "-eth" is a 3rd person ending (he/she/it), e.g. If thy header files fail should be "faileth". "The third person sing. Present, ending in th, as taketh, bringeth &c. is now confined to sermons and grave discourse." - John Hunter, Text-book of English Grammar 1848 My favourite -eth, from the start of Moonlighting's Atomic Shakespeare episode: Good morrow, sir. I'm Lucentio, come hither for to see fair Padua, pleasant garden of great Italy, to seek out and happily begin a course of learning and studies herein. You've mistaken me, sir, for someone who careth. https://youtu.be/ijUr6p8xSBM?t=140 https://youtu.be/ijUr6p8xSBM?t=140
- CalChris 6y agoThou shalt not follow the NULL pointer should probably be appended with and thou shalt not map the zero page.
- beefhash 6y agoKind of hard when the operating system does it for you... https://groups.google.com/d/msg/comp.unix.aix/0dv4N0qmgVQ/tyhnSiOLD0cJ https://groups.google.com/d/msg/comp.unix.aix/0dv4N0qmgVQ/ty...
- CalChris 6y agoOSX (well, OSX ld, not OSX itself) actually does this for you and unmaps the entire low 4GB for good measure, giving new meaning to 32-bit clean.
- beached_whale 6y agoNULL is not the zero page... well at least in the C machine. NULL is NULL. But then again, it does work on systems where it matters(e.g. address 0 is valid and needed)
- greenyoda 6y agoSometimes, the zero page is available to your C program. For example, your C code could be part of the Linux kernel's boot code, or could be running on embedded hardware.
- maallooc 6y ago11. Thou shalt try C++ or Rust
- oconnor663 6y agoI wonder if anyone's ever tried something like "C with slices, destructors, and copy/move semantics".
- Espressosaurus 6y agoThat plus "avoid pure virtual classes", "no use of the heap", "C standard library and header-only libraries only", "compile with no exceptions" gets you close to embedded C++. Except also with classes.
- jmiskovic 6y agoIs this something you would recommend to newcommers? I wouldn't. I can agree that on technical level such subset has a decent set of features and gets the job done. On the other hand when learning how to use this subset, you'll still come across stack overflow answers and other C++ materials that will contradict such methodology, and other coworkers will occasionally challenge that particular stack of choices with their own favourite C++ features. You still have to learn how exceptions work and why avoid them, what is heap and how to disable it, what are pure virtual classes and so on. I dislike the argument that C++ is great because you can limit yourself to appropriate subset. It becomes a different thing while still being called C++, which is miscommunication. If you can brand your subset as EmbeddedC++ and gain widespread audience, then we're closer to good thing. (except there's lot of embedded happening on Linux boards where "normal" C++ is acceptable) My frustration mostly comes from working on huge embedded C++ project where each separate corner of codebase used its own subset of language. This brings down complexity and reduces mental overhead locally, but reasoning about the whole system is impossible.
- suyjuris 6y agoI would much rather recommend something like "C with bounds-checked arrays" than a form of "standard" C++ to newcomers. Yes, StackOverflow will not help much, but I think avoiding the huge amount of features that the rest of C++ brings is well worth it. You are probably not advocating for dumping everything at once onto a beginner, so why not pick a subset that is both really small and gets you quite far? > You still have to learn how exceptions work and why avoid them, what is heap and how to disable it, what are pure virtual classes and so on. Do you mean later on? As I see it, you do not have to learn about the things you do not use and can concentrate on the basics. Once you are comfortable and need to venture out into projects where other parts of C++ are used, you would need to, of course.
- smitty1e 6y agoThe DMR link => http://cm.bell-labs.co/who/dmr/ http://cm.bell-labs.co/who/dmr/
- pwdisswordfish2 6y ago> Beware, in particular, of the subtle and terrible ``All the world's a 32-bit machine'', which is almost true today but shall cease to be so before thy resume grows too much longer. That’s cute. What year was it written?
- mellosouls 6y ago1987 by the look of it. https://groups.google.com/forum/#!msg/comp.lang.c/CYgWkWdWCcQ/thMt3RfByAgJ https://groups.google.com/forum/#!msg/comp.lang.c/CYgWkWdWCc...
- qubex 6y agoYeah... the reference to the abundance of VAXen isn’t something one encounters often this side of the fall of the Berlin Wall.
- pwdisswordfish2 6y agoWhich side is that?
- Y_Y 6y agoThe outside
- pwdisswordfish2 6y agoWhat about HN readers/commenters on the inside?
- rgoulter 6y ago> if thou thinkest ``it cannot happen to me'', the gods shall surely punish thee for thy arrogance This one is a universal experience. :)
- LargoLasskhyfv 6y agoHmhrhm... If thou aren't abide by them, my wrath follows, and make it go BAM! edit: ...my wrath follows, and it shall go BAM!
- asveikau 6y ago#3 sounds extremely obsolete. I don't completely understand what they mean, but perhaps they are thinking pre-C89, when it wasn't as common to list the args in function declarations, so the compiler could not always correctly convert the type? I remember in the 90s some libraries (like X11 headers) would put the types of function arguments inside an ifdef to be able to compile in some archaic place. Edit: or maybe they are thinking of varargs. This could still be an issue with printf today.
- microtherion 6y agoThis should probably carry a date stamp; my guess would be that it dates from 1990 or so. Most of the advice is still good, but I would object to (3): * Excessive casting can be a problem in itself, as it hides genuine type errors (e.g. you think you're casting an int to long, but in reality the variable is a pointer) * Casting NULL is pointless, as it's already defined by the standard to be a pointer constant, compatible with all data pointers. * Much of the language about "prototypes" (a.k.a. standard C) was justified at the time, but no longer reflects reality nowadays. It would have to be a very exotic platform that still uses a pre-ANSI C compiler.
- enriquto 6y agoThis! Casting the output of a function that returns (void*) is usually the first red flag of code not written by an experienced C programmer.
- throwphoton 6y agoWhat can you do with a void pointer without casting it, apart from comparing it to NULL?
- eMSF 6y agoYou can (implicitly) convert it to another pointer type, e.g. int *buf = malloc(sizeof(*buf)); (It's noteworthy that while there's an implicit conversion above, there's no such thing as an implicit cast.)
- microtherion 6y agoYou can assign it to any data pointer variable, and you can printf("%p") it, for example.
- unwind 6y agoThis is a pretty well-regarded answer, with motivation for why you should not cast [1]. Of course it's not something everyone agrees to, but at least a lot of people seem to. [1] https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc https://stackoverflow.com/questions/605845/do-i-cast-the-res...
- lihaciudaniel 6y ago>Thou shalt study thy libraries and strive not to reinvent them without cause, that thy code may be short and readable and thy days pleasant and productive. That's why my teacher ought to go to hell, how many times do I need to say that
- monocasa 6y agoThere's a difference between re-implementing to understand, and re-implementing to ship into production. It's common for a blacksmith to make a set of tools as a exercise, but they'll also commonly get some quality tools to do real work with.
- _sbrk 6y agoI wish more programmers obeyed #7.
- einpoklum 6y agoFor C, obeying #7 is not even that difficult. It's much more of a challenge in C++ and probably Rust (and other languages).
- estebank 6y ago> 7 Thou shalt study thy libraries and strive not to reinvent them without cause, that thy code may be short and readable and thy days pleasant and productive. > Numberless are the unwashed heathen who scorn their libraries on various silly and spurious grounds, such as blind worship of the Little Tin God (also known as ``Efficiency''). While it is true that some features of the C libraries were ill-advised, by and large it is better and cheaper to use the works of others than to persist in re-inventing the square wheel. But thou should take the greatest of care to understand what thy libraries promise, and what they do not, lest thou rely on facilities that may vanish from under thy feet in future. I'm not sure I follow. Why this would be difficult in any language with a usable package manager and a reasonable ecosystem?
- einpoklum 6y agoMost people don't even know what's available to them in the standard library of C++ and under-use things in it. Especially STL algorithms but not just that.
- matt-attack 6y agoCan someone explain #9?
- rramadass 6y agohttps://stackoverflow.com/questions/38035628/c-why-did-ansi-only-specify-six-characters-for-the-minimum-number-of-significa https://stackoverflow.com/questions/38035628/c-why-did-ansi-...
- HankB99 6y agoBetter explanation than mine - thanks I learned something.
- HankB99 6y agoAt some point in the distant past symbol tables allowed symbols up to 6 characters long. Longer names were allowed but anything beyond 6 characters were gone by the time the linker was invoked. So ThisIsAFunction() and ThisIsAnotherFunction() would resolve to ThisIs(). It would hopefully produce an error at link time.
- LoSboccacc 6y agothis and the tao of programming were foundational to my young mind in the nineties, but while the commandments somewhat hold true, the commentary aged a little.
- einpoklum 6y agoThe C++ "equivalent" of this are the "C++ Core Guidelines", which, like the language itself, are a couple of orders of magnitude larger: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md https://github.com/isocpp/CppCoreGuidelines/blob/master/CppC...
- kstenerud 6y agoI was with them until "one true brace style". The rest are good advice.
- komali2 6y agoSame but for perhaps a different reason > As a lamentable side issue, there has been some unrest from the fanatics of the Pronoun Gestapo over the use of the word ``man'' in this Commandment, for they believe that great efforts and loud shouting devoted to the ritual purification of the language will somehow redound to the benefit of the downtrodden (whose real and grievous woes tendeth to get lost amidst all that thunder and fury). When preaching the gospel to the narrow of mind and short of temper, the word ``creature'' may be substituted as a suitable pseudoBiblical term free of the taint of Political Incorrectness. Not sure that was necessary. If you happen to disagree that Language is a valid place to fight for gender equality, you'd better serve your cause ignoring calls to equalize your language, rather than go on an anti-PC rant that smacks of an alt-right /r/unpopularopinion post. Just Another Old Man Yelling At Clouds.
- mturmon 6y agoYep, that remark was an unforced error that has not aged well.
- dragonwriter 6y ago> If you happen to disagree that Language is a valid place to fight for gender equality, you'd better serve your cause ignoring calls to equalize your language, rather than go on an anti-PC rant that smacks of an alt-right /r/unpopularopinion post. What if you happen to want to signal solidarity with the alt-right crowd? Why assume a flamboyant alt-right-style rant is an accidental coincidence? (Nto sure of the 1990 date is for the commandments, the annotations, or both, but in ant case, while it wasn't called the alt-right then, the subculture and attitudes certainly existed at the time this was written; 1990 would have been well into the first wave of it's vigorous embrace of flamboyant attacks on “political correctness” as a signal of group identity, which started in the mid-1980s as I recall.)
- rightbyte 6y ago"If thy header files fail to declare the return types of thy library functions, thou shalt declare them thyself with the most meticulous care, lest grievous harm befall thy program. The prophet Ansi, in her wisdom, hath added that thou shouldst also scourge thy Suppliers, and demand on pain of excommunication that they produce header files that declare their library functions. For truly, only they know the precise form of the incantation appropriate to invoking their magic in the optimal way." This commendment made me afraid of the dark. Was it common in those days to have to guess to calling convention of libfunctions?
- dang 6y agoSee also from 2010: https://news.ycombinator.com/item?id=1876981 https://news.ycombinator.com/item?id=1876981
- Taniwha 6y agoThis probably needs some context ... C at the time was still developing, lots of stuff was optional, parameters were int if you didn't define their type. V6 unix was a decade old and already wouldn't compile on K&R compilers, struct became genuinely unique types (requiring the creation of union, because struct could no longer be tweaked to do the same thing). This was written at the end of that period where most people had an understanding of 'how it should be', while others were still using some of the older idiom ....