The C Programming Language: Chapter 2

Following on from last weeks post, this post is going to go over some of the key points from chapter two of The C Programming Language.

Data types

Unlike many languages, C has a relatively small set of data types. The four main types covered in the chapter are:

  • char: a single byte capable of holding a single character in the local character set.
  • int: an integer, the size of this type varies based on the target system architecture.
  • float: single precision floating point.
  • double: double precision floating point.

A few common data types are absent from the above list, notably booleans. Instead of having a distinct boolean type, C uses zero and non-zero values.

It's also worth briefly mentioning UTF-8. C predates UTF-8 by quite a few years, and many of the examples given in the book assume ASCII character encoding is being used. EBCDIC is briefly mentioned, however neither ASCII or EBCDIC have a character which requires more than a single byte. I suspect many of the examples given in the book may give interesting results if they are fed UTF-8...

printf and data types

Using printf requires a little thought when working with different sized data types. For example if you are printing a long integer, omitting the length field will prevent the correct value being printed:

printf("%d\n", LONG_MAX);  /* don't copy this */

Instead an l should be included to indicate the data type being printed is a long integer:

printf("%ld\n", LONG_MAX);

It's also important to remember to use u instead of d when printing signed integers:

printf("%d\n", UINT_MAX); /* will print -1 */
printf("%u\n", UINT_MAX); /* will print 4294967295 */

Prefix vs postfix operators

Integers can be incremented or decremented using the ++ or -- operator, for example:

int x = 10;
x++;
printf("%d\n", x);  /* print the value of x, which should be 11 */
x--;
printf("%d\n", x);  /* print the value of x, which should now be 10 */

One key point is the increment and decrement operators can be used as either a prefix or postfix operator. The example above uses postfix operators, however you would get the same result with prefix operators. This is not always the case though:

int x;

x = 0;
x = x++ + 5;
printf("%d\n", x);  /* print the value of x (5) */

x = 0;
x = ++x + 5;
printf("%d\n", x);  /* print the value of x (6) */

In the example above x is printed twice, however the final value will differ base on the type of increment operator being used.

Bitwise operators

Unlike some of the other concepts in the chapter, I rarely use bitwise operators when working with other languages. I suspect I will likely revisit this section at some point in the future.