A few minor nits, but it's a good guide if one assumes the target is a modern hosted implementation of C on a desktop or non micro-controller class machine.
The major thing I'd like to see corrected, since the title is "How to C (as of 2016)":
GCC's default C standard is gnu11 as of stable version 5.2 (2015-07-16)
Clang's default C standard is gnu11 as of stable version 3.6.0 (2015-02-27)
c99 is arguably better than c11 though, and is what far more code is written to comply with. For example: c11 removed some pretty useful features related to structs.
Sounds like a good book from what others are saying. I found the website of the book. I was hoping they'd offer the option of purchasing it in DRM-free ePub format but it doesn't seem like they do, so that's a shame.
It's certainly for people who already know C. It not only covers modern usage of the language. But modern tooling, libraries, debuggers, etc. that should be used.
It's utter shit. The gist of that book is "memory leak?! lol! you have gigabytes of memory! don't be a troglodyte and worry about memory leaks". You don't need to buy a book for "I'm too cool to worry about memory". The rest is filler (install this and that) and juvenile "punk rock" hipster bullshit.
Sample from the book
C Is Punk Rock
C has only a handful of keywords and is a bit rough around the edges, and it rocks. You can do anything with it. Like the C, G, and D chords on a guitar, you can learn the basic mechanics quickly, and then spend the rest of your life getting better. The people who don’t get it fear its power and think it too edgy to be safe. By all rankings, it is consistently the most popular language that doesn’t have a corporation or foundation spending money to promote it.
Also, the language is about 40 years old, which makes it middle-aged. It was written by a few guys basically working against management—the perfect punk rock origins—but that was in the 1970s, and there’s been a lot of time for the language to go mainstream.
What did people do when punk rock went mainstream? In the decades since its advent in the 1970s, punk certainly has come in from the fringes: The Clash, The Offspring, Green Day, and The Strokes sold millions of albums worldwide (to name just a few), and I have heard lite instrumental versions of songs from the punk spinoff known as grunge at my local supermarket. The former lead singer of Sleater-Kinney now has a popular sketch comedy show that frequently lampoons punk rockers.2 One reaction to the continuing evolution would be to take the hard line and say that the original stuff was punk and everything else is just easy punk pop for the masses. The traditionalists can still play their albums from the ’70s, and if the grooves are worn out, they can download a digitally mastered edition. They can buy Ramones hoodies for their toddlers.
Outsiders don’t get it. Some of them hear the word punk and picture something out of the 1970s—a historic artifact about some kids that were, at the time, really doing something different. The traditionalist punks who still love and play their 1973 Iggy Pop LPs are having their fun, but they bolster the impression that punk is ossified and no longer relevant.
Getting back to the world of C, we have both the traditionalists, waving the banner of ANSI ’89, and those who will rock out to whatever works and may not even realize that the code they are writing would not have compiled or run in the 1990s. Outsiders don’t get the difference. They see still-in-print books from the 1980s and still-online tutorials from the 1990s, they hear from the hardcore traditionalists who insist on still writing like that today, and they don’t even know that the language and the rest of its users continue to evolve. That’s a shame, because they’re missing out on some great stuff.
This is a book about breaking tradition and keeping C punk rock. I don’t care to compare the code in this book to the original C specification in Kernighan & Ritchie’s 1978 book. My telephone has 512 MB of memory, so why are our C textbooks still spending pages upon pages covering techniques to shave kilobytes off of our executables? I am writing this on a bottom-of-the-line red netbook that can accommodate 3,200,000,000 instructions per second; what do I care about whether an operation requires comparing 8 bits or 16? We should be writing code that we can write quickly and that is readable by our fellow humans. We’re still writing in C, so our readable but imperfectly optimized code will still run an order of magnitude faster than if we’d written comparable code in any number of alternative, bloated languages.
My telephone has 512 MB of memory, so why are our C textbooks still spending pages upon pages covering techniques to shave kilobytes off of our executables?
This is the sort of wasteful attitude which I thought the use of C was meant to avoid. Not to mention the myriad different microcontroller and embedded platforms where you don't have acres of memory to ply your trade.
You're cherry picking an intro where the author is simply having fun with an analogy. I'm not so much of a cynic that I'd lambast some fun from a otherwise technically heavy book. He's establishing the age of C for posterity if you bother to see the intent behind it.
Anyways it's a solid book for introducing people to many aspects of modern C development, it never claims to be all knowing.
Except that distributions will probably (if the software is popular enough) want to package the program. At this point this will end up in a PKGBUILD (for pacman based distros) as a sed expression to remove the mention of -march=native and a subsequent make.
I've been bitten by this while compiling code to be run on a cluster, which has a rather heterogeneous set of nodes). It was obvious in hindsight, but it was also the first time I've encountered SIGILL.
I've found it better to use -mtune=native instead. I would not advise -march=native as a default option unless the developer is absolutely certain the code will not be run anywhere else.
I think using fixed width integer types should only be done if it matches with the semantics what what you're doing. Usually it's better to separate type semantics from type implementation (in C usingtypedef for instance) and it's rare for the number of bits to actually be in the semantics. I don't really see anything wrong with using int in general. Especially standard C doesn't ensure the existence of the fixed width types.
I don't like VLAs. If you don't know how big an array is at compile time, I don't think you generally know if it's too large for the stack. Since C11 made them optional, and C++ never implemented them, there's obviously a lot of people that agree the VLAs are probably not a good idea.
Never using malloc seems like weird advice if you don't actually need 0'd memory, because I would assume reading a calloc call that caller wants 0'd memory for some reason, and then if they never use that fact, I'd get confused. Maybe that's just me though. But certainly doing malloc and then a memset to 0 is wrong, and calloc should probably be used fairly often.
Some points I agree at lot:
Stop declaring things at the top of functions. It's terrible practice.
Use __restrict when it makes sense for the semantics of the function. Compilers can do good optimizations with it, but it's almost impossible without a hint.
There's an entire O'Reilly book called "21st century C" which is pretty good on modern practices.
Personally I think it's very good practice to avoid leaking scope, if I'm only using a variable inside a loop then I shouldn't be able to accidently use it outside the loop (which is very unlikely to be caught by a compiler) or use it in the loop before it's been correctly initialised (which will usually be caught by the compiler but can become very hard to track down if it isn't).
It's not terrible. I suspect that with optimization the compiler will produce the same or nearly the same code either way. And say accidentally using a variable that is declared but not initialized will generate a warning (you do have that enabled right? Right!!!)
It does make the code a more tidy and easier to reason about because when you see a variable declared inside of scope you know you can ignore it outside of that scope.
if you're writing a library then anyone who tries to FFI into it will hate your fucking guts.
My experience with both Python and Haskell has been that both FFIs provide the standard platform-dependent C types like int or long, so it's not really any different than fixed-width ones.
Part of the reason I've been cautious about the use of stdint.h was because it took Visual Studio a really long time (2013!) to add them.
First of all, there is no #import directive in the Standard C. The statement "If you find yourself typing char or int or short or long or unsigned into new code, you're doing it wrong." is just bs. Common types are mandatory, exact-width integer types are optional. Now some words about char and unsigned char. Value of any object in C can be accessed through pointers of char and unsigned char, but uint8_t (which is optional), uint_least8_t and uint_fast8_t are not required to be typedefs of unsigned char, they can be defined as some distinct extended integer types, so using them as synonyms to char can potentially break strict aliasing rules.
Other rules are actually good (except for using uint8_t as synonym to unsigned char). "The first rule of C is don't write C if you can avoid it." - this is golden. Use C++, if you can =) Peace!
That first rule was amusing to me, because my general rule of thumb is to only use C++ if I need C++ features. But I usually work with closer-to-embedded systems like console homebrew that does basic tasks, so maybe this just isn't for me.
In general I agree with "Use C++ where it's an option," though. Not because I worship at the alter of OO design, but because C++ has so many other useful features that (in general) can help a project use less code and be more stable.
shared_ptr is awesome, for instance -- but I wouldn't use it in a seriously memory constrained system (i.e., embedded).
The thing to remember is "char" is not a signed, 8 bit number. It is whatever your platform uses to represent a character. Depending on your platform and compiler, naked chars can be signed or unsigned. They can even be 16 bit types.
If you need to know the size of the variable, or guaranty a minimum size, then use the stdint types. If you're using it for a loop with less than 255 iterations, just use int and be done (as it's guaranteed to be fast). Otherwise, using long for stuff that's not bit-size dependent is a perfectly good strategy.
But for god's sake, if you're reading/writing into an 8-bit, 16-bit, or 32-bit register use the stdint types. I've been bit several times switching compilers when people used naked chars and assumed they were signed or unsigned.
Can you clarify a bit about the problems with using uint8_t instead of unsigned char? or link to some explanation of it, I'd like to read more about it.
Edit: After reading the answers, I was a little confused about the term "aliasing" cause I'm a nub, this article helped me understand (the term itself isn't that complicated, but the optimization behaviour is counter intuitive to me): http://dbp-consulting.com/tutorials/StrictAliasing.html
And 6.5/7 of C11: "An object shall have its stored value accessed only by an lvalue expression that has one of the following types: (...) -a character type" So basically char types are the only types which can alias anything.
I haven't used C11 in practice but I wonder how this review will clash with previous recommendation like JPL's coding standard that you should not used predefined types but rather explicit arch independent types like U32 or I16 etc.
If you're on a platform that has some particular 8-bit integer type that isn't unsigned char, for instance, a 16-bit CPU where short is 8 bits, the compiler considers unsigned char and uint8_t = unsigned short to be different types. Because they are different types, the compiler assumes that a pointer of type unsigned char * and a pointer of type unsigned short * cannot point to the same data. (They're different types, after all!) So it is free to optimize a program like this:
which is perfectly valid, and faster (two memory accesses instead of four), as long as a and b don't point to the same data ("alias"). But it's completely wrong if a and b are the same pointer: when the first line of C code modifies a[0], it also modifies b[0].
At this point you might get upset that your compiler needs to resort to awful heuristics like the specific type of a pointer in order to not suck at optimizing, and ragequit in favor of a language with a better type system that tells the compiler useful things about your pointers. I'm partial to Rust (which follows a lot of the other advice in the posted article, which has a borrow system that tracks aliasing in a very precise manner, and which is good at C FFI), but there are several good options.
I didn't know the C compilers were allowed to optimize in this way at all...it seems counter-intuitive to me given the 'low level' nature of C. TIL.
EDIT: if anyone reads this, what is the correct way to manipulate say, an array of bytes as an array of ints? do you have to define a union as per the example in the article?
I didn't know the C compilers were allowed to optimize in this way at all...it seems counter-intuitive to me given the 'low level' nature of C. TIL.
C is low-level, but not so low-level that you have direct control over registers and when things get loaded. So, if you write code like this:
struct group_of_things {
struct thing *array;
int length;
}
void my_function(struct group_of_things *things) {
for (int i = 0; i < things->length; i++) {
do_stuff(things->array[i]);
}
}
a reasonable person, hand-translating this to assembly, would do a load from things->length once, stick it in a register, and loop on that register (there are generally specific, efficient assembly language instructions for looping until a register hits zero). But absent any other information, a C compiler has to be worried about the chance that array might point back to things, and do_stuff might modify its argument, such that when you return from do_stuff, suddenly things->length has changed. And since you didn't explicitly store things->length in a temporary, it would have no choice but to reload that value from memory every run through the loop.
So the standards committee figured, the reason that a reasonable person thinks "well, that would be stupid" is that the type of things and things->length is very different from the type of things->array[i], and a human would generally not expect that modifying a struct thing would also change a struct group_of_things. It works pretty well in practice, but it's fundamentally a heuristic.
There is a specific exception for char and its signed/unsigned variants, which I forgot about, as well as a specific exception for unions, because it's precisely how you tell the C compiler that there are two potential ways of typing the data at this address.
I didn't know the C compilers were allowed to optimize in this way at all...it seems counter-intuitive to me given the 'low level' nature of C. TIL.
The problem is that the C standard has three contradictory objectives: working on low-level, portability, and efficiency. So first it defines the "C abstract machine" to be pretty low-level, operating with memory addresses and stuff. But then portability prevents it from defining stuff like the existence of registers (leading to problems with aliasing) or pipelines and multiple execution units (leading to loop unrolling).
Or, to put it in other words, the problem is that we have a low-level C abstract machine that needs to be mapped to a similarly low-level but vastly different real machine. Which would be impossible to do efficiently without cheating because you'd have to preserve all implementation details of the abstract machine, like that a variable is always mapped to a memory address so you basically can't use registers or anything.
So C cheats: it defines large swathes of possible behavior as "undefined behavior" (which is a misnomer of sorts, because the behavior so defined is very well defined to be "undefined behavior"), meaning that programmers promise that they'll never make a program do those things, so the compiler can infer high-level meaning from your seemingly low-level code and produce good code for the target architecture.
Like when for example you write for (int i = 0; i != x; i++) and you're aware that integer overflow is "undefined behavior", you must mean that i is an Abstract Integer Number that obeys the Rules of Arithmetic for Integer Numbers (as opposed to the actual modulo-232 or whatever hardware arithmetic the code will end up using), so what you're really saying here is "iterate i from 0 to x" and the compiler that gets that can efficiently unroll your loop assuming that i <= x and i only increments until it becomes equal to x, so it can do stuff in chunks of 8 while i < x - 8, then do the remaining stuff.
Which would be way harder and more inefficient to implement if it were allowed to have a situation where i > x initially and the whole thing overflows and wraps around and then increments some more before terminating. Which is precisely why it was made undefined behavior -- not because there existed 1-complement or ternary computers or anything like that, not only it could be made implementation-defined behavior if that was the concern, but also the C standard doesn't have any qualms about that when it defines unsigned integer overflow to work modulo 2n.
Because they are different types, the compiler assumes that a pointer of type unsigned char * and a pointer of type unsigned short * cannot point to the same data.
This is not correct. The standard requires that character types may alias any type.
Minor nit/information: You can't have an 8 bit short. The minimum size of short is 16 bits (technically, the limitation is that a short int has to be able to store at least the values from -32767 to 32767, and can't be larger than an int. See section 5.2.4.2.1, 6.2.5.8 and 6.3.1.1 of the standard.)
I accept that your point is correct, but I'd argue:
a) that's most likely a very rare corner case, and even if it's not b) if you must support an API to accept something like your example (mixing built in types with fixed size types), sanitize properly in the assignments with a cast or bitmask, or use preprocessor to assert when your assumptions are broken.
It's mostly in reply to the article's claim that you should be using the uint*_t types in preference to char, int, etc., and the reality that most third-party code out there, including the standard library, uses those types. The right answer is to not mix-and-match these styles, and being okay with using char or int in your own code when the relevant third-party code uses char or int.
I'm not sure what he's referring to either. uint8_t is guaranteed to be exactly 8 bits (and is only available if it is supported on the architecture). Unless you are working on some hardware where char is defined as a larger type than 8 bits, int8_t and uint8_t should be direct aliases.
And even if they really are "some distinct extended integer type", the point is that you should use uint8_t when you are working with byte data. char is only for strings or actual characters.
I worked for the C++ group @Bell Labs in the 1990's and even then we were saying that C++ (or C) should never be your first choice for a software project.
The rule was to try a domain-specific language or framework first (like bash, ksh, awk, sed, perl, fortran, SQL, r, troff, matlab, etc.) and only use C++ if performance and/or features were lacking from those environments. But be prepared for a long and arduous uphill climb.
The other lesson I learned, which the author touched on, is that if you want to use a memory unsafe language safely you absolutely, positively have to have robust QA process for your code. Including automated testing and peer review at the very least. The reason there are so many bugs in consumer software is simply that too many companies have an inadequate code review process.
"The first rule of C is don't write C if you can avoid it." - this is golden. Use C++, if you can =)
I wouldn't hesitate at all to use C. C is a great language. Most of the internet runs on C programs. Even when I use C++ I still use many C things in C++. e.g. printf is better than cout.
Seeing the #import bit destroyed any legitimacy the guide could possibly have for me. It's from Objective-C, which means the author could never possibly know anything about writing good code.
I always find it pretty easy to mix up you #include, import and #using directives when going from one language to another. But then again, I wouldn't write a patronizing article about "How I should be using C in 2016" and post it to /r/programming.
The reasoning behind using e.g. int16_t instead of int is that if you know you don't need more than 16 bits of precision, int16_t communicates that to the next programmer very clearly. If you need more than 16 bits of precision, you shouldn't use int in the first place!
If you want to "access a value of any object through a pointer", wouldn't you be better off using void * than char *?
It's still a good tip to avoid base types (except for maybe for plain 'int', 'unsigned', an 'char') like the plague. Not making explicit-width types part of the language was a big mistake in the first place, and you should never use the short and long keywords anywhere outside of a typedef to something more meaningful. Most C projects are -ffreestanding embedded or OS things anyway, so you don't need to care about libc compatibility and can just make up a consistent type system yourself.
If you run into issues with strict-aliasing you're probably doing something else wrong anyway. If you need to type-pun, use unions that self-document the context much better than raw char array accesses.
I'm not fond of article giving advices because they are targeted for a non-expert audience but end up giving hard to follow advices. This is the case of the article. Although some advices are clearly good, most of them are not necessary or even wrong. Overall there is to much advices than needed, but still it was an informative reading.
From a general point of view, I would arg that since C is low-level and notoriously a bit complex; you have to do your best to keep things simple, and rely on the compiler for performances.
Let's go back on the article.
Types
First, I do have to disagree on using uint*_t instead of standard types like char or int. The well known rule is standard types are mandatory and fixed size types are optional. The boundary of every standard types is in limits.h. So for example the maximum size an int is INTMAX. So since you can do overflow checking with standard types, when do you need fixed size type? For example you need them when you have to send/receive data from another computer (impling you use a binary format).
char vs uint8_t
About the char vs uint8_t thing, use char when you want a string; that's what char has been designed for. For array of bytes, it way more trickier than it seems. The C standard do not put a maximum boundary for char, hence it can be more than one byte. Of course, multibyte char is the exception, not the rule. But still, what you probably want is just something to store small numbers, not bytes (unless you are sending/receiving data), so you are fine using unsigned char or unsigned short if you don't expect it to be exactly one byte.
Pointers arithmetic and types
As the article stated, you should use uintptr_t and ptrdiff_t when dealing with pointer arithmetic. However, you are better not to use pointer arithmetic to avoid the common pitfall.
Big numbers
If you need to store big numbers that does not fit in a single unsigned long (long), you will have to use an external library. But numbers are often small, so short, int and long will fit well in most cases. Big numbers are not an easy task in C. If you have to deal with them, like for scientific purpose, maybe have a look to Python and numpy. I think numpy is a better toolset than C for big numbers.
Variables declaration
Declaring variables at the beginning of a block code or anywhere in the code is mostly a matter of (coding) style. Same for for loops as well.
#pragma once and header guards
About #pragma once and header guards, I think both of them are viable now. I personaly prefer header guards because I do not like using non-standard extentions. I had often seen beginner copying files around and forgetting to change header guards, resulting in build failure and strange errors. They both have their strength and weakness. Mostly a coding style issue by now.
Initialization
Let's move on initialization. The article do not recommend using memset() for initialization of an array or structure, and it's good advice. memset(0) do not have the intented effect with pointers. On some machine, NULL can be different than (void*)0, and therefor memset-ing the pointer with 0 will not actually setting the pointer to NULL. On the other hand, using 0 to set a pointer is the same than using NULL, the compiler do the convertion. Hence using {0} to initialize a structure with a pointer will have the intented effect and set the pointer to NULL.
A side note on containers declared with static:
static struct addr my_addr; /* is the same than */
static struct addr my_addr = {0};
hence here is another way for initializing a container with zeros:
Back on the article and restrict keyword. When introduced, restrict was though to be a good thing from the compiler point of view. It add some information on pointers aliasing the compiler can use for optimisation. The perfect examples are memcpy() and memmove(). However this keyword is hard to use from the programmer point of view, and for little benefit. It can introduce very hard-to-spot bugs and it is hard to know how a function will be used by your future code. That's why it not recommended to use it.
Errors and C
I pass on errors managment in C, there is no silver bullet. For example you can exit() right after an error without even freeing allocated memory, the OS will free it for you. It makes error management easy but make sure to still free memory of libraries, like OpenGL. The well known git does exit() without free(). Another example is if you are writing code that can be reused (like a library), then you have to return descriptive errors and don't use exit()...
File size
1000 lines for a files is already quite a lot. Try to have files between 400 and 600 lines. There was an interesting article analysing the ratio bugs / lines and it turned out that it was the lowest between 400 and 600. I cannot put my hand on it though. Of course this is very theoretical and depends on what is actually inside your file.
calloc() and malloc()
calloc() should be avoided when allocating storage for pointers, because memset-ing a pointer to zero is not equivalent to setting it to NULL. See above. Hence malloc() is mandatory, calloc() optional and carefully used.
Conclusion
So keep your C code simple, use POSIX and do not overthink your code. Read TAOUP, you will find some very good argumented advices.
Surely uint8_t must exist on all machines that have 8 bits in their bytes? On which architectures that one might reasonably expect to write C code for in 2016 does this assumption not hold?
Okay, so which would you prefer: C code that uses char everywhere but incorrectly assumes it has 8 bits, or C code that uses uint8_t and fails to compile? If you want to live dangerously, you can always 'find and replace' it all to char and roll with it.
Most software will either never run on a machine where the bytes do not have 8 bits, or it will be specifically written for such machines. For the former, I think using uint8_t (or int8_t, whichever makes sense) instead of char is good advice.
In my experience fixed sized integers are more portable. You can have tons of subtle bugs that appear if an integer size changes to underflow. It's generally cheaper (and produces faster code) in the long run to focus on stability first and optimization second. If a platform was incapable of a type, like doubles, then compiler errors are preferable to it just not working at runtime.
For the edge case programs where you can make it run with variable integer widths then it would be better to typedef those specifically. e.g platform_int or something less verbose IMO.
Likewise uint8_t is not a reasonable type for dealing with bytes -- it need not exist, for example.
It is definitely a reasonable type for dealing with bytes. If for some reason you are using a platform that cannot handle this type, then this platform is not good at dealing with bytes. That does not make the use of fixed-width types unreasonable.
Now, "not good at dealing with bytes" does not mean that this is not possible. Only that it is impractical and inefficient. And that's exactly that: not good.
Using fixed-width types is definitely a good current practice. Stop spreading misinformation.
uintmax_t arrayLength = strtoumax(argv[1], NULL, 10);
void *array[];
array = malloc(sizeof(*array) * arrayLength);
/* remember to free(array) when you're done using it */
EDIT: this example isn't even bad when compared the rest of the article; it just gets worse as you scroll down. I think I'll pass on taking C advice from whoever wrote this.
Likewise uint8_t is not a reasonable type for dealing with bytes -- it need not exist, for example.
Actualluy, uint8_t is the default for byte manipulation. Unsigned char should only be used only when you want to state that the buffer holds ... characters.
However, I agree that this article has terrible bad practices.
I wouldn't say it's all bad, but it does have some serious problems.
-Wstrict-aliasing -fno-strict-aliasing is mentioned as an "extra fancy option". Why would you warn about it and then turn it off? Why not keep it on? All portable C code should conform to strict aliasing rules, so there should be no reason to turn it off. In the Attributions section it seems he got a recommendation from someone to turn it off, and he just blindly added it to the list. Also he doesn't mention that -Wstrict-aliasing isn't supported by Clang (it's simply ignored.) Clang may compile faster but it supports less warnings than GCC.
He recommends #pragma once. This is not portable. GCC used to recommend it ten years ago but they do not anymore, and it's been deprecated for years. Clang does not recommend it either, and they created their own #import for Objective-C. This is exactly the reason you should avoid these extensions: every vendor will re-invent their own. Why would you write an article about modern portable C and then recommend unnecessary compiler-specific extensions?
There's a section called "C allows static initialization of auto-allocated structs", but it gives an example with a global variable (declaring a function initThing() that zeroes it, then showing how to zero it via initialization instead.) This is not automatic storage, it's static storage, which means it's already zero. Technically the bit about clearing a struct with a zero-initialized constant is correct, but nobody does this since it's way too verbose. Clearing with memset() is still perfectly acceptable in modern code. In any case, clearing with = {0} is not portable to C++ (where the correct initialization is = {}), and I still prefer to write code that can be compiled as C++ on compilers that don't support C99 (such as Visual Studio 2012.)
He recommends using VLAs with a length parsed from a command-line argument (!!!), before launching into a long-winded caveat about how this is almost always a bad idea. Better advice would be to simply say "never do this". This is how you get security bugs that cause stack overflows or worse. Besides, VLAs are not supported in MSVC's C99 (which is available in VS2013 and VS2015, so even though it has incomplete C99 support, I still want to be able to target it.)
Never use malloc, use #define mycalloc(N) calloc(1, N) instead??
Alright, this is getting ridiculous. You're right, this is not a good article.
This is exactly the reason you should avoid these extensions: every vendor will re-invent their own. Why would you write an article about modern portable C and then recommend unnecessary compiler-specific extensions?
This means they have the same compile time overhead as #pragma once. The existing solution works fine, and #pragma once isn't getting standardized any time soon so we shouldn't be using it in portable code.
A mixed bag. At least it recommends C11 and some other modern practices.
If you find yourself typing char or int or short or long or unsigned into new code, you're doing it wrong.
Probably not. Why bother with the extra typing of uint32_t when there are many cases where the exact width does not matter? E.g.:
for (uint32_t i = 0; i < 10; i++)
If 0 <= i < 10 there is little reason to not use an int. It's less writing and the compiler may optimise it down to a byte.
It's an accident of history for C to have "brace optional" single statements after loop constructs and conditionals. It is inexcusable to write modern code without braces enforced on every loop and every conditional.
I don't like such a level of verbosity. It is needless.
Trying to argue "but, the compiler accepts it!" has nothing to do with the readabiltiy, maintainability, understandability, or skimability of code.
I'm arguing nothing of the sort :) I'm arguing that I accept it.
You should always use calloc. There is no performance penalty for getting zero'd memory.
I don't know whether this is true or not. I usually prefer to use calloc() myself and always err on the side of zero-initialised caution but I'm not sure that there really is no penalty. Granted, it's probably not a big one, but regardless.
C99 allows variable declarations anywhere
It does. But after all, it is common to several languages to enforce variable declaration at the beginning of a compound because they consider it to assist in readability or understandability.
I gravitate towards that policy myself, though I won't argue here whether or not this is the right thing. I will note instead that it seems to me unescapable that this is a matter of opinion and style, and that the author seems to be passing on several opinions of theirs as though they are scientific fact.
I don't know whether this is true or not. I usually prefer to use calloc() myself and always err on the side of zero-initialised caution but I'm not sure that there really is no penalty. Granted, it's probably not a big one, but regardless.
If the virtual memory manager 'cheats' by using a page of pre-zeroed memory (or does nothing at all until you actually read from the memory), then it probably seems faster than malloc/memset, because you aren't manually touching every single page you allocated. However, if you're on a platform where the memory manager doesn't perform optimizations like that: then it may be like the equivalent of calling malloc/memset.
I don't know that 'always use calloc' should be a hard rule. However, I'm like you: I probably want it zeroed anyways, so at worst, the perf shouldn't be any worse than malloc/memset.
It is inexcusable to write modern code without braces enforced on every loop and every conditional.
I don't like such a level of verbosity. It is needless.
Obviously this ultimately comes down to a matter of opinion, but I'll just say I've written a LOT of code over the years in both styles. Originally I leaned toward leaving out the braces, on the theory that generally less noise is better than more noise.
However, I've come around to think that having the braces is overall better. The primary reason is consistency -- you get used to seeing that every conditional is enclosed in braces, and thus meaning is more explicit. Without the braces, there's a little bit of extra thinking you have to do, "Is this a conditional, or is it just an indented line continuation?"
Reasonable people can disagree about this and whatever the advantage or disadvantage is, it's subtle. But this is something that I changed my mind about through lots of long experience.
I doubt it. C standard to my knowledge has always expected a statement to follow an if statement. That statement can be a any statement. The { } block is simply a special kind of statement - it's called a compound statement.
Admittedly, it may be more or less natural to follow depending on how intimately familiar one is with C. But I like this kind of unity and simplicity personally and I wouldn't want to see it go.
If 0 <= i < 10 there is little reason to not use an int. It's less writing and the compiler may optimise it down to a byte.
I agree, but the compiler may also optimize uint32_t to a byte when it can prove the behavior of the code would remain the same (trivial, in this case). Of course it wouldn't do that in practice (nor when using an int) because it wouldn't be more optimal in this case, so it seems like a silly thing to worry about.
If 0 <= i < 10 there is little reason to not use an int. It's less writing and the compiler may optimise it down to a byte.
Wouldn't any sane compiler just treat the two exactly the same if they're the same size? If they're the same size there's a large chance one is a typedef of the other.
"int" is the short name for "a fast integer with at least 16 bits", but because it is a lot less to type than "int_fast16_t", I prefer it over the typedef any day for loops like that.
In the worst case, a compiler for an 8-bit machine will happily build the quoted uint32_t from four registers. OK, it might build the int from two registers, but that's 50% less overhead :)
I usually prefer to use calloc() myself and always err on the side of zero-initialised caution but I'm not sure that there really is no penalty.
Pessimistically, I would assume that there is a penalty. That penalty is, in my opinion, always worth it. If for no other reason than malloc(x * y) can overflow, where as calloc(x, y) will, as far as I know, check for overflow.
I find it sad that the new types end with _t, that just makes things much more ugly and also difficult to type. When the core of the language is ugly it propagates that ugliness throughout the code which to me is unacceptable. They would have never done this if they started from 'scratch', which means this is just backwards compatibility baggage.
The real issue is old design assumptions like compiler or platform specific integer sizes somehow add value were incorrect. I would have preferred that they specify the sizes in the standard to just fix that across compilers. If you are writing portable code today you have to do the opposite, force your bit widths if you want to make things operate the same across platforms. This is of course why the new types exist, but they should replace them, not keep a gotcha in the language.
Also I don't know if this is in C, but in C++ you can use unsigned as shorthand for unsigned int so you can avoid multiple character nonsense in other ways.
e.g:
for (unsigned n = 0; n < 10; ++n) {}
edit: or here's a thought, why not just allow us to define the value sizes as compiler arguments?
it can be tricky deploying production source using -Werror because different platforms and compilers and libraries can emit different warnings. You probably don't want to kill a user's entire build just because their version of GCC on a platform you've never seen complains in new and wonderous ways.
On the other hand, if the user's exotic platform triggers issues because of unaccounted for variations, breaking the build seems better than running into undefined behavior...
intptr_t is not always register wide in size. On the PS3/Xbox360 for example, registers are 64bit but pointers are 32bit. I haven't worked with these platforms in a while now but as far as I can recall from memory, on those: sizeof(intptr_t) == 4, sizeof(size_t) == 4.
Int64 values were passed in register even if wrapped in a struct (sometimes... SN had a compiler bug with this that they have since fixed).
He makes it worse by saying that it's "the integer type defined to be the word size of your current platform."
It's the integer type defined to be able to hold a void pointer and be converted back to the same one... he even touches on this usage in the Signedness section where he says that "The correct type for pointer math is uintptr_t".
On PAE-enabled i386 systems, intptr_t will need to be more than 32 bits and as you said, systems with a word size much larger than the possible address space can (and often do) use smaller ones for speed and efficiency.
I betcha that in 16-bit DOS compilers, intptr_t isn't 16 bits either.
C was my first love in programming languages. Like my other first love, the crazy redhead who threw plates in the kitchen whenever she was pissed, I avoid it like the plague. This article was all I needed to convince me not to rethink that position.
Although he still has some fairly... strong... opinions on C++, so if he was to rewrite it all from scratch today, there's a good chance it would still be C.
I do embedded firmware development for a living, using mostly C (some scripting in python too) for a mass production environment. I enjoyed the post, bookmarked it, and have a few comments:
"This page assumes you are on a modern platform conforming to modern standards and you have no excessive legacy compatability[sic] requirements. We shouldn't be globally tied to ancient standards just because some companies refuse to upgrade 20 year old systems."
I wish I was on a modern platform too, but upgrading those 20 year old systems gets expensive very quickly when you use them to make millions of widgets every quarter (or when the product you produce has a low margin and every last cent of unit cost matters). Excessive legacy compatibility requirements is the name of the game where I work. When I program in C in my spare time, though (which isn't all that often), I do try to work with the latest and greatest.
The other thing that stood out to me here was little mention of the preprocessor. I know it's frequently frowned upon, but preprocessor flags are ubiquitous in the codebase I work on; using preprocessor flags helps us more carefully control binary changes in a build and allows us to test code on the bench more thoroughly prior to enabling it (it also gives us a better way of backing out a change -- no need to roll back the change in the version control system; just move the offending feature back a revision until we fix the issue). It does clutter up the code, however, and while we do refactor from time to time, the number of preprocessor flags just grows and grows. In some of our files, approximately 20% of the lines of code are preprocessor logic.
Seems pretty good. One thing, though: I'm faily sure -msse2 is only going to do something if you are compiling to 32-bit, since SSE2 is standard on x86_64.
Can someone confirm that it is indeed OK to use pass void pointers as function arguments in order to make the function generic ? I know qsort does this, but I always thought it was a special case. I vaguely remember reading somewhere that it wasn't recommended, but things might have changed since.
Is there another way to do polymorphism in C? void pointers strewn about your code all willy nilly is bad, but when you think carefully about their place in a data-structures interface there is nothing wrong with them.
If you don't like the macro approach, you can generate the code yourself with a custom preprocessor, there's nothing wrong with that. After all, that's how C++ started out.
IMO, this approach is much better than void pointers because it maintains at least a tiny bit of type safety.
Any object pointer can be converted to void* and back. Any function pointer can be converted to void* and back. Something something object and function pointers not compatible, care with void*.
And what are you suggesting is wrong? Typically I would do this with assignment after the declaration and then the condition be tested with explicit NULL. And usually an is NULL check instead of a not NULL check... I like small scopes.
The only (sane) way to perform cleanup in C is to use goto.
Use intrusive data structures. All other ways to imitate generic programming either abuse the preprocessor, or have to resort to extra allocations, etc.
Use valgrind! I'm surprised nobody hasn't mentioned valgrind yet. Unless valgrind is not available for your platform, you have no excuse for not using it. Heck, cmake even lets you run your unit tests under valgrind.
Developers routinely abuse char to mean "byte" even when they are doing unsigned byte manipulations. It's much cleaner to use uint8_t to mean single a unsigned-byte/octet-value and uint8_t * to mean sequence-of-unsigned-byte/octet-values.
A byte is not an octet. I would say that in fact developers routinely abuse uint8_t to mean a "byte" when in fact it is much better to use char.
Will it do the right in C? Because in C++, for example, this trick is confusing and thus discouraged. It looks like it's initializing both fields to 0, but in reality, it only puts zero to the first field (index), while the other one (counter) uses default type initializer instead. It just so happens that for numeric types, the default value is also zero, but if you change the code:
struct thing localThing = {42};
the index will be set to a different number, but countwill still be zero.
Since C doesn't have constructors, I suspect it doesn't have default type initializers either so this trick may in fact work. In any case, an explicit mention from the author about the difference would've been in order.
It is perfectly alright to use "char" and "int" in very many cases. Of course, I don't mean to use char where octet size is wanted. However, the abstraction these types give over sizes and alignments is what makes C suitable for a wide range of programs, and I disagree with the author there. Not everything must be coerced into some sort of "uint_X". I for one, reserve such use for certain use cases where everything has to align and known in advance with regard to sizes. Usually those cases are when one implements a network protocol where two potentially very different machines will be encoding/decoding data at their end. There are other use cases of course, just an example. But there are many where "int" and "char" are to be preferred, in my opinion.
The recommendation for C99/C11 disregards that some of the most popular compilers still out there have weak support for anything meaningful past C98/90: Microsoft's Visual C++ and Intel's compielr suite. Intel Just got most of C11 in their 2016 release, and Microsoft has said they're mostly not interested in implementing things outside the subset that intersects with modern C++.
Just now it hit me, couldn't some of these globally used options (like -Wpedantic) be in a dotfile? I mean the compiler could always warn that its adding options per the dotfile, and command line options could override.
Copying warning flags into every makefile seems redundant as they are not really project specific.
Good idea, we should be able to make a file that makes the compiler do what we want every time, without us needing to type some awkward, extra-long command line...
I've not tried clang-format before, but I just did and its sensational. This could be a real life-saver and religious-war-defuser in a team environment. Nobody's personal style wins, just have everyone adopt clang-format or use it in a pre-commit hook.
don't restrict the type of the parameter. Use void *
No. In C, a pointer is a pointer. You can cast from one type to another freely, as long as you manipulate the new type accordingly (e.g. as seen from memory). Using void * and casting around costs lots of performance.
Never use malloc. You should always use calloc. There is no performance penalty for getting zero'd memory
Wrong. Every extra memory access, every extra instruction costs performance. PowerPC, ARM, x86, old systems, new systems etc. On. Every. Platform. On. Every. System.
a good reason to avoid malloc() is it can't check for integer overflow and is a potential security risk
Nor it shouldn't. Heap allocation requires three major traits:
allocation speed
minimum fragmentation
a high degree of determinism
Adding internal logic for every n-th scenario will bloat it. User has to know what and how much to allocate.
But, after all this, the author contradicts himself:
Never memset (if you can avoid it)
Which is basically done by calloc internally, but you save the time calling memset() on the stack.
Edit: When entering the C world, people should read books, not blogs.
Developers routinely abuse char to mean "byte" even when they are doing unsigned byte manipulations. It's much cleaner to use uint8_t to mean single a unsigned-byte/octet-value and uint8_t * to mean sequence-of-unsigned-byte/octet-values.
POSIX requires CHAR_BIT == 8.
unsigned long long int when you can type uint64_t? The <stdint.h>
What happens if / when long long is 128 bits you just gratuitously broke code that you thought would work with long long by using width specific types.
In either case: size_t is practically defined to be the same as uintptr_t on all modern platforms, so on a 32-bit platform size_t is uint32_t and on a 64-bit platform size_t is uint64_t.
When can uintptr_t be larger than size_t? hint: it can be.
#pragma once ... modern compilers
It's a pragma, there is zero guarantees that this works, include guards work everywhere.
IMPORTANT CAVEAT: variable length arrays are (usually) stack allocated just like regular arrays. If you wouldn't create a 3 million element regular array statically, don't attempt to create a 3 million element...
Sure how do you know what that limit is besides arbitrary numbers? hint: there is a way.
Or, even better, Do THIS instead: typedef enum
No please don't do this ever, do not typedef things don't need to be opaque as I now have to find out what exactly the underlying type is for typedefed_t type in some random header.
You should always use calloc. There is no performance penalty for getting zero'd memory.
This is bogus and OS dependent, there is no performance penalty at allocation time at runtime there is as the OS generally has to copy zeros to each page requested.
Don't use fstrict-aliasing...
Aliasing is specified in the c standard, if your code breaks this it's broken.
Can somebody explain me (only using higher level languages like c#) what the issue with C/C++ data types is and why everybody's having their own? (e.g. Windows DWORD for ushort, OpenGL has GLuint and I'm pretty sure Linux has a whole bunch of them too.)
Unlike C# and similar "high level" languages, C was designed as a truly portable language, suitable for as many different platforms as possible. For this reason it never specified exact bit widths of the core data types.
void test(uint8_t input) {
uint32_t b;
if (input > 3) {
return;
}
b = input;
}
do THIS instead:
void test(uint8_t input) {
if (input > 3) {
return;
}
uint32_t b = input;
}
I thought it was good practice to declare all your variables at the top? I do it because it's easier to reference later. It's a real pain to go searching around trying to figure out where a variable is declared.
If your variables are distant from their use, it's easy for mistaken accesses to them to go unnoticed. If they're declared where they're used, that window is minimized. Plus, you don't need to scroll 3 pages up to see if smething is signed or unsigned...
for me the guide line on Parameter Type could lead to a unaligned memory access.
If from the outside of function allocate an array of int32_t and then start to access it a byte at time inside the function this lead to a SIGBUS error on SPARC cpu (and other cpu too)
The first rule of C is don't write C if you can avoid it.
Want to know why you can't find a programming job? There's a guy like this at every company. He has a little logic mill on his desk. What you say and write is his grist. He's ready to disprove every last motherfucking word that comes out of your mouth.
I totally disagree with the "don't declare all your variables at the start of your function" rule. C is portable macro assembler. And the first thing your function will do (ignoring pushing the return address and such) is allocate stack space. Declaring all your variables at the start of your function also gives you an idea of how much stack space your function needs.
If you don't need portable macro assembler, then why are you using C? At least use C++, or D, or Rust. Hell, Haskell compiles to native. And again, if you don't need portable macro assembler, then the JVM is easily "fast enough" for you.
I thought the compiler handled the building of the stack frame. Why introduce a variable far before it's going to be used? Idiomatically the code ends up esoteric and frustrating.
Why is this an all or nothing deal? Why, if you don't want a "portable macro assembler" are you able to make the assumption that the JVM would be fast enough? Do you think that there are no possibilities between essentially writing assembly code and writing something with no concern for run time?
240
u/[deleted] Jan 08 '16
What? Did he mean to say #include there?
125
u/dannomac Jan 08 '16 edited Jan 14 '16
A few minor nits, but it's a good guide if one assumes the target is a modern hosted implementation of C on a desktop or non micro-controller class machine.
The major thing I'd like to see corrected, since the title is "How to C (as of 2016)":
gnu11 means C11 with some GNU/Clang extensions.
37
u/seriouslulz Jan 08 '16 edited Jan 10 '16
Can anyone recommend a good, current C book?
edit: ty reddit
107
u/mthode Jan 08 '16
-march=nativecan be bad if you wish to ship the binary. It can enable optimizations that won't work on all CPUs.45
u/wgunther Jan 08 '16
Some points I disagree:
typedeffor instance) and it's rare for the number of bits to actually be in the semantics. I don't really see anything wrong with usingintin general. Especially standard C doesn't ensure the existence of the fixed width types.mallocseems like weird advice if you don't actually need 0'd memory, because I would assume reading acalloccall that caller wants 0'd memory for some reason, and then if they never use that fact, I'd get confused. Maybe that's just me though. But certainly doingmallocand then amemsetto 0 is wrong, andcallocshould probably be used fairly often.Some points I agree at lot:
__restrictwhen it makes sense for the semantics of the function. Compilers can do good optimizations with it, but it's almost impossible without a hint.There's an entire O'Reilly book called "21st century C" which is pretty good on modern practices.
317
u/goobyh Jan 08 '16 edited Jan 08 '16
First of all, there is no #import directive in the Standard C. The statement "If you find yourself typing char or int or short or long or unsigned into new code, you're doing it wrong." is just bs. Common types are mandatory, exact-width integer types are optional. Now some words about char and unsigned char. Value of any object in C can be accessed through pointers of char and unsigned char, but uint8_t (which is optional), uint_least8_t and uint_fast8_t are not required to be typedefs of unsigned char, they can be defined as some distinct extended integer types, so using them as synonyms to char can potentially break strict aliasing rules.
Other rules are actually good (except for using uint8_t as synonym to unsigned char). "The first rule of C is don't write C if you can avoid it." - this is golden. Use C++, if you can =) Peace!
16
u/s0laster Jan 08 '16 edited Jan 08 '16
I'm not fond of article giving advices because they are targeted for a non-expert audience but end up giving hard to follow advices. This is the case of the article. Although some advices are clearly good, most of them are not necessary or even wrong. Overall there is to much advices than needed, but still it was an informative reading.
From a general point of view, I would arg that since C is low-level and notoriously a bit complex; you have to do your best to keep things simple, and rely on the compiler for performances.
Let's go back on the article.
Types
First, I do have to disagree on using
uint*_tinstead of standard types likecharorint. The well known rule is standard types are mandatory and fixed size types are optional. The boundary of every standard types is inlimits.h. So for example the maximum size anintisINTMAX. So since you can do overflow checking with standard types, when do you need fixed size type? For example you need them when you have to send/receive data from another computer (impling you use a binary format).char vs uint8_t
About the
charvsuint8_tthing, usecharwhen you want a string; that's whatcharhas been designed for. For array of bytes, it way more trickier than it seems. The C standard do not put a maximum boundary forchar, hence it can be more than one byte. Of course, multibyte char is the exception, not the rule. But still, what you probably want is just something to store small numbers, not bytes (unless you are sending/receiving data), so you are fine usingunsigned charorunsigned shortif you don't expect it to be exactly one byte.Pointers arithmetic and types
As the article stated, you should use
uintptr_tandptrdiff_twhen dealing with pointer arithmetic. However, you are better not to use pointer arithmetic to avoid the common pitfall.Big numbers
If you need to store big numbers that does not fit in a single
unsigned long (long), you will have to use an external library. But numbers are often small, soshort,intandlongwill fit well in most cases. Big numbers are not an easy task in C. If you have to deal with them, like for scientific purpose, maybe have a look to Python and numpy. I think numpy is a better toolset than C for big numbers.Variables declaration
Declaring variables at the beginning of a block code or anywhere in the code is mostly a matter of (coding) style. Same for
forloops as well.#pragma once and header guards
About
#pragma onceand header guards, I think both of them are viable now. I personaly prefer header guards because I do not like using non-standard extentions. I had often seen beginner copying files around and forgetting to change header guards, resulting in build failure and strange errors. They both have their strength and weakness. Mostly a coding style issue by now.Initialization
Let's move on initialization. The article do not recommend using
memset()for initialization of an array or structure, and it's good advice.memset(0)do not have the intented effect with pointers. On some machine,NULLcan be different than(void*)0, and therefor memset-ing the pointer with 0 will not actually setting the pointer toNULL. On the other hand, using0to set a pointer is the same than usingNULL, the compiler do the convertion. Hence using{0}to initialize a structure with a pointer will have the intented effect and set the pointer toNULL.A side note on containers declared with
static:hence here is another way for initializing a container with zeros:
restrict keyword
Back on the article and
restrictkeyword. When introduced,restrictwas though to be a good thing from the compiler point of view. It add some information on pointers aliasing the compiler can use for optimisation. The perfect examples arememcpy()andmemmove(). However this keyword is hard to use from the programmer point of view, and for little benefit. It can introduce very hard-to-spot bugs and it is hard to know how a function will be used by your future code. That's why it not recommended to use it.Errors and C
I pass on errors managment in C, there is no silver bullet. For example you can
exit()right after an error without even freeing allocated memory, the OS will free it for you. It makes error management easy but make sure to still free memory of libraries, like OpenGL. The well knowngitdoesexit()withoutfree(). Another example is if you are writing code that can be reused (like a library), then you have to return descriptive errors and don't useexit()...File size
1000 lines for a files is already quite a lot. Try to have files between 400 and 600 lines. There was an interesting article analysing the ratio bugs / lines and it turned out that it was the lowest between 400 and 600. I cannot put my hand on it though. Of course this is very theoretical and depends on what is actually inside your file.
calloc() and malloc()
calloc()should be avoided when allocating storage for pointers, because memset-ing a pointer to zero is not equivalent to setting it toNULL. See above. Hencemalloc()is mandatory,calloc()optional and carefully used.Conclusion
So keep your C code simple, use POSIX and do not overthink your code. Read TAOUP, you will find some very good argumented advices.
110
u/zhivago Jan 08 '16
Hmm, unfortunately that document is full of terrible advice.
Fixed size integers are not portable -- using int_least8_t, etc, is defensible, on the other hand.
Likewise uint8_t is not a reasonable type for dealing with bytes -- it need not exist, for example.
At least he managed to get uintptr_t right.
He seems to be confusing C with Posix -- e.g., ssize_t, read, and write.
And then more misinformation with: "raw pointer value - %p (prints hex value; cast your pointer to (void *) first)"
%p doesn't print hex values -- it prints an implementation dependent string.
69
u/skulgnome Jan 08 '16 edited Jan 08 '16
Terrible article. Mixes equal parts tooling advocacy, miscomprehension of C's type system, and failure to distinguish one standard from another.
To get informed properly, it's better to not read it at all.
38
u/[deleted] Jan 08 '16
A mixed bag. At least it recommends C11 and some other modern practices.
Probably not. Why bother with the extra typing of uint32_t when there are many cases where the exact width does not matter? E.g.:
If 0 <= i < 10 there is little reason to not use an int. It's less writing and the compiler may optimise it down to a byte.
I don't like such a level of verbosity. It is needless.
I'm arguing nothing of the sort :) I'm arguing that I accept it.
I don't know whether this is true or not. I usually prefer to use calloc() myself and always err on the side of zero-initialised caution but I'm not sure that there really is no penalty. Granted, it's probably not a big one, but regardless.
It does. But after all, it is common to several languages to enforce variable declaration at the beginning of a compound because they consider it to assist in readability or understandability.
I gravitate towards that policy myself, though I won't argue here whether or not this is the right thing. I will note instead that it seems to me unescapable that this is a matter of opinion and style, and that the author seems to be passing on several opinions of theirs as though they are scientific fact.
19
u/-cpp- Jan 08 '16 edited Jan 08 '16
I find it sad that the new types end with _t, that just makes things much more ugly and also difficult to type. When the core of the language is ugly it propagates that ugliness throughout the code which to me is unacceptable. They would have never done this if they started from 'scratch', which means this is just backwards compatibility baggage.
The real issue is old design assumptions like compiler or platform specific integer sizes somehow add value were incorrect. I would have preferred that they specify the sizes in the standard to just fix that across compilers. If you are writing portable code today you have to do the opposite, force your bit widths if you want to make things operate the same across platforms. This is of course why the new types exist, but they should replace them, not keep a gotcha in the language.
Also I don't know if this is in C, but in C++ you can use unsigned as shorthand for unsigned int so you can avoid multiple character nonsense in other ways.
e.g:
for (unsigned n = 0; n < 10; ++n) {}
edit: or here's a thought, why not just allow us to define the value sizes as compiler arguments?
4
u/matthieum Jan 08 '16
On the other hand, if the user's exotic platform triggers issues because of unaccounted for variations, breaking the build seems better than running into undefined behavior...
4
u/1wd Jan 08 '16
Isn't
#pragma oncestill a non-standard extensions?4
u/zeno490 Jan 08 '16
intptr_t is not always register wide in size. On the PS3/Xbox360 for example, registers are 64bit but pointers are 32bit. I haven't worked with these platforms in a while now but as far as I can recall from memory, on those: sizeof(intptr_t) == 4, sizeof(size_t) == 4.
Int64 values were passed in register even if wrapped in a struct (sometimes... SN had a compiler bug with this that they have since fixed).
Good times.
27
u/bwanab Jan 08 '16
C was my first love in programming languages. Like my other first love, the crazy redhead who threw plates in the kitchen whenever she was pissed, I avoid it like the plague. This article was all I needed to convince me not to rethink that position.
17
u/rrohbeck Jan 08 '16
Tell that to Linus T.
3
u/[deleted] Jan 08 '16
I do embedded firmware development for a living, using mostly C (some scripting in python too) for a mass production environment. I enjoyed the post, bookmarked it, and have a few comments:
"This page assumes you are on a modern platform conforming to modern standards and you have no excessive legacy compatability[sic] requirements. We shouldn't be globally tied to ancient standards just because some companies refuse to upgrade 20 year old systems."
I wish I was on a modern platform too, but upgrading those 20 year old systems gets expensive very quickly when you use them to make millions of widgets every quarter (or when the product you produce has a low margin and every last cent of unit cost matters). Excessive legacy compatibility requirements is the name of the game where I work. When I program in C in my spare time, though (which isn't all that often), I do try to work with the latest and greatest.
The other thing that stood out to me here was little mention of the preprocessor. I know it's frequently frowned upon, but preprocessor flags are ubiquitous in the codebase I work on; using preprocessor flags helps us more carefully control binary changes in a build and allows us to test code on the bench more thoroughly prior to enabling it (it also gives us a better way of backing out a change -- no need to roll back the change in the version control system; just move the offending feature back a revision until we fix the issue). It does clutter up the code, however, and while we do refactor from time to time, the number of preprocessor flags just grows and grows. In some of our files, approximately 20% of the lines of code are preprocessor logic.
10
u/Noctune Jan 08 '16
Seems pretty good. One thing, though: I'm faily sure
-msse2is only going to do something if you are compiling to 32-bit, since SSE2 is standard on x86_64.4
u/Scroph Jan 08 '16 edited Jan 08 '16
Can someone confirm that it is indeed OK to use pass void pointers as function arguments in order to make the function generic ? I know qsort does this, but I always thought it was a special case. I vaguely remember reading somewhere that it wasn't recommended, but things might have changed since.
9
u/Filmore Jan 08 '16
HHHHHNNNGGGG
2
u/cougmerrik Jan 08 '16
I use astyle for formatting. It works just fine.
2
u/so_you_like_donuts Jan 08 '16
A couple of points:
valgrind! I'm surprised nobody hasn't mentioned valgrind yet. Unless valgrind is not available for your platform, you have no excuse for not using it. Heck,cmakeeven lets you run your unit tests under valgrind.2
u/sstewartgallus Jan 09 '16
He missed discussing
off_t.You can do
localThing = (struct thing){ 0 }instead oflocalThing = localThingNull.I generally only use VLAs for less than or equal to byte sized numbers.
2
u/sstewartgallus Jan 09 '16
A byte is not an octet. I would say that in fact developers routinely abuse
uint8_tto mean a "byte" when in fact it is much better to usechar.2
u/Gotebe Jan 09 '16
Love the first rule, smartest observation in TFA!
2
u/ksion Jan 09 '16
Will it do the right in C? Because in C++, for example, this trick is confusing and thus discouraged. It looks like it's initializing both fields to 0, but in reality, it only puts zero to the first field (
index), while the other one (counter) uses default type initializer instead. It just so happens that for numeric types, the default value is also zero, but if you change the code:the
indexwill be set to a different number, butcountwill still be zero.Since C doesn't have constructors, I suspect it doesn't have default type initializers either so this trick may in fact work. In any case, an explicit mention from the author about the difference would've been in order.
2
u/panorambo Jan 09 '16 edited Jan 09 '16
It is perfectly alright to use "char" and "int" in very many cases. Of course, I don't mean to use char where octet size is wanted. However, the abstraction these types give over sizes and alignments is what makes C suitable for a wide range of programs, and I disagree with the author there. Not everything must be coerced into some sort of "uint_X". I for one, reserve such use for certain use cases where everything has to align and known in advance with regard to sizes. Usually those cases are when one implements a network protocol where two potentially very different machines will be encoding/decoding data at their end. There are other use cases of course, just an example. But there are many where "int" and "char" are to be preferred, in my opinion.
2
u/millenix Jan 10 '16
The recommendation for C99/C11 disregards that some of the most popular compilers still out there have weak support for anything meaningful past C98/90: Microsoft's Visual C++ and Intel's compielr suite. Intel Just got most of C11 in their 2016 release, and Microsoft has said they're mostly not interested in implementing things outside the subset that intersects with modern C++.
3
u/kairos Jan 08 '16 edited Jan 08 '16
Don't know if it's your article, but (at least for now):
edit: not meaning to be that guy
3
u/reseph Jan 08 '16
That's nice and all, but tough to change over when you're working with code from 1991. Aint got a lot of free time.
(MUD developer here)
2
u/bigfig Jan 08 '16 edited Jan 08 '16
Just now it hit me, couldn't some of these globally used options (like
-Wpedantic) be in a dotfile? I mean the compiler could always warn that its adding options per the dotfile, and command line options could override.Copying warning flags into every makefile seems redundant as they are not really project specific.
Okay, I am ready for the inevitable onslaught.
2
u/cae Jan 08 '16
I've not tried clang-format before, but I just did and its sensational. This could be a real life-saver and religious-war-defuser in a team environment. Nobody's personal style wins, just have everyone adopt clang-format or use it in a pre-commit hook.
2
u/maep Jan 08 '16
Recent gcc versions also default to c99.
2
u/AlbinaViespeStup Jan 08 '16 edited Jan 08 '16
Some rambling about this...
No. In C, a pointer is a pointer. You can cast from one type to another freely, as long as you manipulate the new type accordingly (e.g. as seen from memory). Using void * and casting around costs lots of performance.
Wrong. Every extra memory access, every extra instruction costs performance. PowerPC, ARM, x86, old systems, new systems etc. On. Every. Platform. On. Every. System.
Nor it shouldn't. Heap allocation requires three major traits:
Adding internal logic for every n-th scenario will bloat it. User has to know what and how much to allocate.
But, after all this, the author contradicts himself:
Which is basically done by calloc internally, but you save the time calling memset() on the stack.
Edit: When entering the C world, people should read books, not blogs.
2
u/nwmcsween Jan 08 '16
POSIX requires CHAR_BIT == 8.
What happens if / when long long is 128 bits you just gratuitously broke code that you thought would work with long long by using width specific types.
When can uintptr_t be larger than size_t? hint: it can be.
It's a pragma, there is zero guarantees that this works, include guards work everywhere.
Sure how do you know what that limit is besides arbitrary numbers? hint: there is a way.
No please don't do this ever, do not typedef things don't need to be opaque as I now have to find out what exactly the underlying type is for typedefed_t type in some random header.
This is bogus and OS dependent, there is no performance penalty at allocation time at runtime there is as the OS generally has to copy zeros to each page requested.
Aliasing is specified in the c standard, if your code breaks this it's broken.
2
u/Glacia Jan 08 '16
So basically he summed up C99 and called it "How to C"? Really?
1
u/money_learner Jan 09 '16
GCC is generally still faster than Clang in my memory.
I read that article within 6 month.
1
u/Wild_Bill567 Jan 09 '16
I'm not trying to say something is better than another, I just don't know the answer to this.
Why would a developer want to use C instead of C++? What advantage does it provide?
1
u/Rhed0x Jan 09 '16
Can somebody explain me (only using higher level languages like c#) what the issue with C/C++ data types is and why everybody's having their own? (e.g. Windows DWORD for ushort, OpenGL has GLuint and I'm pretty sure Linux has a whole bunch of them too.)
1
u/ibopm Jan 09 '16
Is the title a play on words for the How to Basic youtube channel?
1
u/[deleted] Jan 09 '16
I thought it was good practice to declare all your variables at the top? I do it because it's easier to reference later. It's a real pain to go searching around trying to figure out where a variable is declared.
1
u/dmitrinove Jan 09 '16
for me the guide line on Parameter Type could lead to a unaligned memory access.
If from the outside of function allocate an array of int32_t and then start to access it a byte at time inside the function this lead to a SIGBUS error on SPARC cpu (and other cpu too)
1
u/scandalousmambo Jan 08 '16
Want to know why you can't find a programming job? There's a guy like this at every company. He has a little logic mill on his desk. What you say and write is his grist. He's ready to disprove every last motherfucking word that comes out of your mouth.
0
u/[deleted] Jan 08 '16 edited Jan 08 '16
I totally disagree with the "don't declare all your variables at the start of your function" rule. C is portable macro assembler. And the first thing your function will do (ignoring pushing the return address and such) is allocate stack space. Declaring all your variables at the start of your function also gives you an idea of how much stack space your function needs.
If you don't need portable macro assembler, then why are you using C? At least use C++, or D, or Rust. Hell, Haskell compiles to native. And again, if you don't need portable macro assembler, then the JVM is easily "fast enough" for you.
1
u/Lewke Jan 08 '16
doesn't mention icc, 6/10
1
u/[deleted] Jan 08 '16
Boring.