February 2nd, 2011

To become a good C programmer

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. Here is an entry that list 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 ;) !

 

@