Fabien Sanglard's non-blog

  




To become a good C programmer

February 2nd, 2011


The question


Every once in a while I receive an email from a fellow programmer asking me what language I used for one of my games and how I learned it. Hence, I thought it may help a few people to list here the best things to read about C. If you know of other gems, please email me or add a comment at the bottom of the page.

The answer (you can skip this)


As I mentioned it in a previous entry, all the commercial 3D engines I wrote so far are 95% C89 (aka "Standard C", aka "ANSI C").
I picked C89 instead of C99 because some compilers still don't support fully C99…and to be able to compile on iOs, Windows and Xbox 360 was a mandatory from day one.

Depending on the compiling platform, the 5% remaining are Objective-C (iOS) or C++ (Windows, Mac OS X) to bind the engine to the native inputs/output. Unexpectedly the C vs C++ proved quite controversial on reddit. The two real reasons were:

Were those "good" choices? I think in the end the only valid questions are "Did you ship it?" and "Was it fast?". Considering the incredible frame rate achieved (some people mentioned experimenting motion sickness while playing Shmup) I think I made the right calls.

Bad C readings (stop skipping)


I'm going to start with the things I didn't take too seriously: Internet tutorials, blogs and almost anything brought by Google (yes, it includes this article). I usually considered those sources unreliable and potentially harmful.

Like a lot of people in the industry I used to Google way too often. Overtime I found the illusion of speed and the inaccuracy of the answers to be counter-productive.

No website is as good as a good book. And no good book is as good as a disassembly output.

Excellent C readings


"C Programming Language" (aka: K&R)

The classic and first book you should read about C.

It will be easy to pick up as it is a 272 pages, 386 grams book. Short and full of well explained code samples it was written by the fathers of the language Kernighan and Ritchie themselves. It is all you need to know about C…for the first few weeks. It is fun to read, keeps things short and will get you going in no time. You will probably skip the Annex A (about obscure things like promotions, decaying, conversions and other useless things) and Annex B about the C Library…and I think it's ok for the beginning. This book makes C appears very small and simple so it is very encouraging to learn.

If you keep on practicing and learning you will soon hit some strange situations. Like for example:


    unsigned int   ui_one       =  1 ;
    signed   int   i_one        =  1 ;
    signed   short s_minus_one  = -1 ;
	
    if( s_minus_one > ui_one)
		printf("-1 > 1 \n");
	
    if( s_minus_one < i_one) 
		printf("-1 < 1 \n");

    #./run
    #
    # -1 > 1 
    # -1 < 1 

In the previous code sample, due to "integral promotion" -1 was once evaluated to be greater than 1 and then smaller than 1. C has plenty of case like this when the language cannot longer "do stuff" for you.

There are also plenty of subtleties:



    extern void foo(void);
    void (*f)();
	
    f = &foo;   // Valid 
    f = foo;    // Valid too ! (syntactic sugar)
	
    f();        // Calls f
    (*f)();     // Calls f too ! (syntactic sugar)




Or the array/pointer/decaying special cases...

	
	int array[] = {0,1,2,3,4} ;
	int* pointer = array;
	
	if (sizeof array == sizeof pointer)
		printf("This will never be printed !!");
	
	if (sizeof(int*) == sizeof &array[0])
		printf("This will be printed !!\n");
	
	if (&array[2] - &array[0] == 8)
		printf("This will never be printed either, result is 2 not 8!!");



When you hit the point where you understand that you actually know very little about C (and that the Annex A is way too slim), it will be time to pickup the second book.

Expert C Programming

This book is fantastic because it will bring your attention to what happens under the hood in a very entertaining way.
Through numerous bug anecdotes and trivia (mostly NASA based) the reader will be introduced again to integral promotion, subscripting, decaying and many other C marvels. This book is so captivating that you will probably read the 353 pages within a night and be dissapointed it was so short.



Now willing to do deep and become a good C programmer, you should acquire the last book you will ever need:

C: A Reference Manual

This is the ultimate C/C89/C99 book. The true cold boring truth that you will deal with from now on. You can put K&R and ECP back on the shelves and keep this one besides the screen monitor. Anything you want to know is there.






The C Standard library


February 6th 2013 : Two years have passed since I wrote this article. The three books mentioned remain the best in my opinion ... but what about the C Standard Library ?

The best book to master the C Library is with no doubt "The Standard C Library" by P.J. Plauger : Not only it comes with an implementation of the entire library, it also discuss design decisions and provides historical perspectives (ever wondered why C performed all floating operations in double ? Or how errno came to existence ? This book has the answers.

It covers in details the 15 modules of C89: assert.h, ctype.h, errno.h, float.h, limits.h, locale.h, setjmp.h, signal.h, stdarg.h, stddef.h, time.h, and discuss at length the "big four": stdio.h, stdlib.h, string.h and math.h
.
The only two big things missings are the coverage of C99 integral types (intypes.h and stdint.h) which are paramount in order to write portablecode and C11's threads.h which is equaly important considering the emergence of multi-core CPUs. For now I haven't found anything better but I welcome reader's suggestions.



Additional readings


id Software codebase

Of course reading books is not enough. To read great C code will help tremendously. My favourite is id Software's 3D engines codebase: Doom, Quake, Quake 2, Quake 3, Wolfenstein 3D iPhone and Doom iPhone. While I read them I wrote memos for myself which I later turned into articles (Doom, Quake,Wolfenstein 3D iPhone and Doom iPhone).



Sh*t My Dad Says

Try to maintain an healthy life and read some fun stuff for a change ;) !






Add a comment



Name Homepage
E-mail
(Will not appear online)
Comment



Comments (10)


#1 - sylvainulg - 02/03/2011 - 04:21
I'd tend to recommend -Wall as an additional reading. Enabling sufficient warnings in C is very important to have reminders of pitfalls, such as "this loop will never end because you're comparing a unsigned to -1, and that's always true", or "I doubt you want to assign a new value to X here, and more likely want to compare X to that value. Use if ((x=foo(bar)) ... if that really was your intent".
#2 - Wondersonic - 02/03/2011 - 06:55
Another great post, thanks!!!
#3 - Ben - 03/10/2011 - 14:54
Thx, this will help me a lot learning C :) I'm just diving into it.
#4 - Antonio - 05/27/2011 - 10:48
Hi, i'm reading the c programming language book by Kerninghan and Ritchie, you said that this book is easy, i don't think so, especially if you try to do the exercises using the techniques explained.
Yes there are chapters that are easy and others don't, like the last example of the pointers chapter and the exercise 5-20.
It is only 200 pages and is written by the author of C, this is why i like this book.
I think this is the only book a C programmer need, after it will be a good idea read the alghoritms in C book by Sedgewick Robert. and when you start to build some project code complete by Steve McConnell.
#5 - Albert1 - 12/10/2011 - 04:17
It seems you like to use OOP principles in C... I think you should read "Object Oriented Programming with ANSI C" by Axel-Tobias Schreiner, now freely downloadable at http://www.cs.rit.edu/~ats/books/ooc.pdf
#6 - Albert1 - 12/10/2011 - 06:51
Another good book is "C Interfaces and Implementations: Techniques for Creating Reusable Software" by David R. Hanson.
#7 - René Hansen - 12/23/2011 - 17:56
Good read and thanks for the book recommendations. Only have K&R at the moment, will check out the other two.
#8 - anon - 03/28/2012 - 23:10
I recommend two other books:

1. Steve Maguire's Writing Solid Code (good practices for reliable C programming)
2. P.J. Plauger's The C Standard Library (implementation of clib without the platform cruft you will see on your home machine sources)
#9 - booirror - 10/01/2012 - 09:37
great post!I have read "Expert C Programming ",I like reading this book
#10 - noop - 11/18/2012 - 08:14
Hi. I'm one of those C++ programmers who use C++ as a convenient extension to C.It's really good, if used carefully. After reading discussion on reddit I agree with GoAwayStupidAI user, C++ can be used to generate code at least as efficient as C code in less time. Fact that C++ lets you do a lot of really horrible stuff doesn't mean that you can't constrain youself to a subset that really works.

 

@2011