The C Programming Language: Chapter 1
I'm now one week into The C Programming Language by Brian Kernighan and Dennis Ritchie. So far I've been very impressed with the book, it's much more hands on than I expected, which is great because I tend to learn by writing code.
I've now finished the first chapter of the book, however I've still got a few exercises to complete. The source code for the exercises should be on GitHub shortly. In the mean time the rest of this post is going to cover a few initial thoughts now I'm one week in.
Initial thoughts
The first chapter is fairly broad, and introduces a range of different topics. Because C has been so influential, many of the topics like for loops and variable scope should be familiar if you're coming from another language, however there are definitely some points which are worth noting.
Double or single quotes
Unlike languages like Python where single and double quotes can be used interchangeably, double quotes and single quotes have different meanings. In C single quotes identify a single character, with the numeric value normally corresponding to an ASCII character:
int character = 'A';
printf("%d\n",character); /* prints 65 */
Double quotes on the other hand create a string literal. This variable will be a character array with a null byte as the last character:
char characters[2] = "A";
printf("%d, %d\n", characters[0], characters[1]); /* prints 65 0 */
Optional brackets
Like many languages curly brackets ({
) can be omitted under certain
circumstances, for example if a loop only has a single statement:
for (i = 0; i < 4; i ++)
foo[i] = i * i;
While this is optional, many of the examples in the book use this shortcut. This can quickly become a problem if you forget to add brackets when adding an additional statement. For example the code below will only run the last line once because it's not part of the for loop:
for (i = 0; i < 4; i++)
printf("%d\n", i);
foo[i] = i * i;
It's also very easy to add an extra ;
if brackets are omitted. The code below
is a good example of this:
for (i = 0; i < 4; i++);
printf("%d\n", i);
Note: while this code will compile, printf
will only be run once and will
print 4
.
String manipulation
I've been using Python for quite a few years now. As a result, it's very easy
to take many of the built in features for granted. For example, one of the
exercises asks you to remove trailing whitespace from stdin
. In Python you
could just use rstrip, however the C implementation
requires a little bit more work.