The C Programming Language: Chapter 2
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 */
l should be included to indicate the data type being printed is a
It's also important to remember to use
u instead of
d when printing signed
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
-- operator, for
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.
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.