In progress

K&R Chapter 2: Do you fear operators?

The C Programming Language — Chapter 2 Brian W. Kernighan & Dennis M. Ritchie → Oct 21, 2026 ~23 min read

variable · constant · limits.h · floats.h · ctype.h · sign extension · truncation · string literal · string constant · #define · enum · wraparound · cast · two's complement · ones' complement · hexadecimal · octal · binary · EBCDIC · ASCII · static typing · dynamic typing · type inference · machine dependence · null terminator · automatic variable · integer division · truncation · overflow · underflow · short circuit · propositional logic · type conversion · cast · prefix · postfix · bitwise operators · arithmetic operators · arithmetic shift · logical shift · mask · getbits · ASCII arithmetic · hexadecimal · place value · precedence · software metrics

Companion log: I’ll take my chances with C types & operators, Sir. All the raw facts from this chapter live there. This post is about what I made of them.

Introduction

Still on the basics of C. This time I’ll share the interesting bits from types, operators and expressions. We’ll get into what types are available to us in C, and what operators there are, ranging from the familiar arithmetic ones to the less familiar bitwise operations.

I’ve changed the approach slightly for this chapter. Most of it is fact-based, the kind of thing you look up rather than read, so I’ve pulled all of that into a separate log you can skim like a cheat sheet. What’s left here is what I actually found interesting, the code I wrote, and the quirks that aren’t obvious.

It’s worth mentioning that certain sentences or paragraphs of the book tell a lot about how much thought and effort went into making explanations accurate and concise. For instance K&R says things like “Names in different enumerations must be distinct. Values need not be distinct in the same enumeration” and then moves on like nothing happened. Believe me when I say it took me more than a minute to digest this. No fluff, no padding. I was tempted to pick a leaf and write these notes the same way, but that would probably only serve to feed my ego. The aim is communication, not compression and self-aggrandizement 1. So I’ll try to explain anything I think took me a while to understand. It’s a feature, not a bug.

Variables

A variable is a named piece of storage. The name is how you refer to it in source, and the type tells the compiler how big that storage is and how to interpret the bits inside it. In C this matters more than in most languages people start with, because nothing is checked for you at runtime, so the declaration is the only contract there is.

The naming rules are almost intuitive. Don’t start names with an underscore, because library routines use that convention, and only the first 31 characters of an internal name are guaranteed to be significant.

It’s easy to compare variables in C with how variables are handled in other languages like Java. In fact each language has its own naming rules, though some are similar, but it’s safer not to assume when you’re unsure. Languages have different philosophies at their core, and variables, among other things, are among the biggest indicators of this. Having static typing, dynamic typing or type inference gives you an idea of how strict and safe a language is. I feel we might be slipping into the classic “which language is the best” argument so let’s not digress.

Types

C’s basic types are char, int, float and double, with short, long, signed and unsigned as qualifiers on top. The thing that surprised me is how little the standard actually promises: it fixes minimums and an ordering, but the real sizes are machine-dependent. That’s why <limits.h> and <float.h> exist 2, and why fixed-width types like uint32_t turn up so often in embedded code. So it’s probably smart to keep an eye out for code that is machine dependent. The second chapter of CS:APP details the different ranges of numerical types for 32-bit and 64-bit computers, blog coming soon on that.

Coming from languages where a number is just a number, like Python, having to think about whether a value fits, whether it’s signed, and what happens at the boundary is the part that takes adjusting to. It is a bit more to think about, but I can see how it can save you hours of debugging. By being more explicit about your variables, the compiler can catch certain bugs early enough instead of you suffering with them at runtime.

What’s interesting is how easily this idea has permeated the programming language spectrum. Java took C’s static typing and made it stricter and portable by clearing ambiguities in the sizes outright. Assembly sits at the other end, where there are no types at all, only bit patterns and the instructions you choose to apply to them, which is really what C is thinly wrapping. And more recently the traffic has gone the other way: JavaScript grew TypeScript, and Python grew type hints, slowly creeping into languages that were designed without types, one version update at a time.

I personally think that this pattern of directly or indirectly adding types to languages is a manifestation of an important fact: the more explicitly we understand and express what our code is doing, the easier it becomes to build reliable systems on top of it. As software grows more complex, what we leave implicit becomes increasingly difficult to ignore. I wonder how this principle will hold up in the age of AI, where we’re increasingly building systems whose inner workings we don’t fully understand. It’s certainly an engineering challenge, but engineering is, after all, about solving problems effectively. The question, then, is whether we can engineer our way around this lack of understanding, or whether understanding what we build is so fundamental to engineering that abandoning it would mean ceasing to engineer at all.

Constants and declarations

Most of this is lookup material and it’s in the log. Maybe a few tidbits worth mentioning.

A string constant is actually one more byte than it looks, because of the terminating '\0'. "hello" has five characters and takes six bytes. This null terminator, as it’s called, is used to mark the end of a string. Forgetting this is a classic way to walk off the end of an array, and even worse is forgetting both the '\n' from terminal input in addition to the '\0'.

External and static variables are initialized to zero for you while local or automatic variables are not, so uninitialized locals hold garbage values, as evidenced in the output of this code.

#include <stdio.h>
int a;
int b;
int c;
int main() {
  printf("a:%d\nb:%d\nc:%d", a, b, c);
  return 0;
}
a:0
b:0
c:0

Reliably zero. Now the same thing as locals:

#include <stdio.h>

int main() {
  int a;
  int b;
  int c;
  printf("a:%d\nb:%d\nc:%d", a, b, c);
  return 0;
}
a:32513
b:452477328
c:0

Note that c happening to be 0 in the second case is luck. Unless you want your program to run on luck, it’s worth reviewing your code rather than its output alone. Undefined values can look correct, which means this is the kind of bug dependent on circumstance, and we really want our program’s output to depend only on its inputs, a leaf worth picking from functional programming.

Arithmetic operators

The arithmetic operators are the ones most people are familiar with, + - * / %, however some have quirks.

Integer division truncates. 5 / 2 is 2, not 2.5, and nothing warns you. And % doesn’t work on floating point at all. Believe me when I say these can be some of the most infuriating bugs you’ll face. The illusion that everything is working as it should only makes matters worse, testing your patience far more than the average bug. I imagine these are especially easy to miss in abstract expressions, where the consequences of a seemingly harmless operation can ripple through an entire computation.

I feel like it would be a sin to miss this, so here it is. The direction of truncation for / and the sign of the result for % are machine-dependent when the operands are negative, as is what happens on overflow or underflow. So -7 / 2 and -7 % 2 are not portable. Imagine having such a bug and only one machine type to debug with.

Relational and logical operators

Relational operators (> >= < <=), equality (== !=) and logical operators (&& || !) are where C meets discrete mathematics directly.

“These are the same predicates and connectives from propositional logic, and everything that applies there applies here: De Morgan’s laws, truth tables, implication rewritten as !p || q. If you’ve done a discrete maths course, you already know how to simplify a tangled if condition, you just haven’t applied it to code yet. It’s one of the few places where the maths transfers one to one with no translation.”

Is what I would have said if coding was as simple as the statement makes it seem to be. Alas it isn’t. Depending on the complexity of a task, using logical operators can get pretty abstract really quick. I for one know some expressions have taken me more than 10 minutes to untangle partly cause I’m considering precedence but mainly cause I keep losing my train of thought and starting afresh.

A relational or logical expression in C has the numeric value 1 if true and 0 if false, so you can do arithmetic on comparisons. And && and || short-circuit, evaluating left to right and stopping as soon as the answer is known. This is what makes if (p != NULL && p->x) safe.

Type conversions

The short version is that C converts narrower operands to wider ones automatically, because that doesn’t lose information. Anything that might lose information, like float to int, is legal but may warn. Casts let you force it explicitly, and the cast produces a converted value without altering the variable itself.

Increment and decrement

++ and -- are unusual in that they come in prefix and postfix forms, and the difference is when the value is taken relative to when the variable changes. An operator that doesn’t just change a value, but specifies when to change it. ++n increments first and gives you the new value; n++ gives you the old value and increments after. In a statement where the value isn’t used, they’re identical.

Bitwise operators

This was the most interesting section of the chapter for me, partly because it shows up alot my embedded class work. Bit manipulation is where C stops pretending to be a high-level language and reveals its true nature, much to the horror of anyone looking for a safe, soft, user-friendly programming experience.

Intimidating as it may seem at first, though, it’s hardly as difficult as it appears. I’ve even come to suspect that bit manipulation is considered difficult partly because people avoid learning it precisely because it seems difficult. This creates a vicious feedback loop: it’s too hard, so it’s not worth learning, so I never learn it, so it remains hard. The more I expose myself to these concepts, through the second chapter of CS:APP and its exercises (slow and steady wins the race type of thing), the less intimidating they become. Which makes me wonder how many supposedly difficult topics owe their reputation less to their inherent complexity and more to our reluctance to engage with them.

Bitwise operation sim

Bit manipulation, one column at a time

Eight bits, two numbers, one operator. Press Step and the result is worked out a single column at a time, the same way the hardware does it.

Operator

Try an idiom

Right-shifting an unsigned value always fills with zeros, but right-shifting a signed value fills with sign bits on some machines and zeros on others. Same code, different answer, depending on the machine. You can read this in more detail in 2.1.9 Shift Operations in C of CS:APP, where it talks about logical versus arithmetic right shifts.

Related, prefer x & ~077 over x & 0177700 3. Both do the same thing on a 16-bit int, but only the first says what you actually mean.

And don’t confuse the bitwise operators with the logical ones. x & y works bit by bit; x && y evaluates truth and short-circuits. 1 & 2 is 0, but 1 && 2 is 1.

Exercise 2-3: converting hex strings to integers

Let’s go through an excercise from the book to workout our type and operator muscles, no pun intended.

Write a function htoi(s) which converts a string of hexadecimal digits (including an optional 0x or 0X) into its equivalent integer value. The allowable digits are 0 through 9, a through f, and A through F.

// Exercise 2-3. Write a function htoi(s), which converts a string of
// hexadecimal digits (including an optional 0x or 0X) into its equivalent
// integer value. The allowable digits are 0 through 9, a through f, and A
// through F.

// 0-9 = 48 - 57
// A-Z = 65-90
// a-z = 97-172

#include <stdio.h>

int to_hex(char *s, int lim, int num[]);
int get_string(char *s, int lim);

int main() {
  int lim = 1024;
  char s[lim];
  int num[lim];

  int count = get_string(s, lim);

  int hex = to_hex(s, count, num);
  printf("%d", hex);
}

// Converts hex string to an integer, expects digits to be large enough
int to_hex(char *s, int lim, int digits[]) {
  char c;
  int j = 0;   // pos in character array s
  int i = 0;   // pos in digits
  int sum = 0; // sum of product of digits and their place values
  int has_0x = 0;

  // If string starts with '0x' or '0X', skip those
  if (s[j] == '0' && (s[j + 1] == 'x' || s[j + 1] == 'X')) {
    j = 2;
    has_0x = 1;
  }

  // Loop through the characters to the last excluding '\n'
  for (; j < lim - 1; j++) {
    c = s[j];

    if (c >= 48 && c <= 57) { // Ascii range 0-9
      digits[i] = c - 48;

    } else if (c >= 65 && c <= 70) { // Ascii range A-F

      //  A is Ascii value 65, 65 - 55 is 10 which is equivalent to converting
      //  hex value A to 10
      digits[i] = c - 55;

    } else if (c >= 97 && c <= 102) { // Ascii range a-f

      // a is Ascii value 97, 97-87 = 10, equivalent to converting hex a to 10
      digits[i] = c - 87;

    } else {
      digits[i] = 0;
    }
    i++;
  }

  // Multiply each digit by its place value and add to the sum
  if (has_0x) {
    j -= 2;
  }
  int pv_num = 0; // number at place value
  int pv = j - 1; // place value

  for (int i = 0; i <= j; i++) {
    pv_num = 1;

    for (int k = 0; k < pv; k++) {
      pv_num *= 16;
    }

    sum += digits[i] * pv_num;
    pv--;
  }

  return sum;
}

int get_string(char *s, int lim) {
  char c;
  int i = 0;
  while ((c = getchar()) != '\n' && c != EOF) {
    if (i < lim - 1) {
      s[i] = c;
      i++;
    } else {
      break;
    }
  }

  if (c == '\n') {
    s[i] = c;
    i++;
  }
  s[i] = '\0';
  return i;
}

This one is a good illustration of the skeleton-first approach, because the problem splits cleanly into stages that can each be tested on their own. The steps I worked through:

Read the input into a buffer. A separate get_string function that reads characters until newline or EOF, guards against overrunning the buffer, and null-terminates. Doing this as its own function meant I could confirm input handling worked before touching any hex logic.

Skip the optional prefix. If the string starts with 0 followed by x or X, start reading from index 2 instead of 0, and remember that you did since it changes the digit count later.

Map each character to its value. This is the part that makes the ASCII ranges matter. Digits 0 to 9 are 48 to 57, so subtracting 48 gives the value. A to F are 65 to 70, and hex A is 10, so subtracting 55 gives the value. a to f are 97 to 102, so subtracting 87 does the same. So each range merits its own offset, sounds like a case for the case control flow statement 4.

Combine digits by place value. Each digit is multiplied by 16 raised to its position from the right, and summed. This is where the off-by-one lives, because the place value depends on how many digits there actually are after the prefix was skipped.

Hold tight for the ASCII arithmetic. c - 48 and c - 55 look like magic numbers, but they’re just the distance from the start of a contiguous range in the character set, which is the same trick as c - '0' written less readably.

Assignment, conditional expressions and precedence

Remember all these are available in the log.

An assignment is an expression and has a value. A lot of C idiom can be unpacked from this line, while ((c = getchar()) != EOF), and your expectations for the output of such a line greatly depend on operator precedence.

And more importantly, C does not specify the order in which operands are evaluated, except for &&, ||, ?: and ,. In x = f() + g();, either function may run first. If one alters something the other depends on, the result depends on your compiler. It’s better to write code that entirely avoids such situations.

Lessons from the exercises

The approach from the chapter 1 notes still holds: visualize, note the steps, break the steps down as small as possible, then code. What chapter 2 added was discipline about the order of those steps.

Start with a complete end-to-end pipeline with minimal functionality. Input to output, almost nothing in between. This lets you test continuously as you add features, so bugs surface while the surrounding code is still small enough to hold in your head.

Do a dry run by hand, on paper, with a clear example. Start with the base case, then work towards the edge cases. This forces any assumptions you had into the open. At each step, ask yourself what you need to remember. That question tells you what state to save and what you can throw away, and it turns the hand trace into a named set of variables almost automatically.

Write the logic as human comments or pseudo-code first.

// for each character:
//   copy it to the current output line, advance col
//   if it's a blank, remember this position as last-break-point
//   if col reaches N:
//       if we saw a blank -> break the line THERE (back at last-break-point)
//       else -> force a break here (long word case)
//       reset col for the new line

Then fill in the code, three or four lines at a time, testing between each. Since the skeleton already runs end to end, every addition is testable immediately. When stuck, shrink the input and add a trace print to narrow down where it goes wrong. This plus the skeleton makes debugging dramatically easier than writing half a program and guessing where the bug is.

I learned this the hard way. I made the mistake of diving into the interesting bits first, without the skeleton, because I thought I already had the solution. You can see the evidence in the old, abandoned versions of exercises 1-21 and 1-22. I started applying this approach properly in 1-22, and hopefully you’ll notice the difference in the code.

I probably fell into this trap because of the excitement that comes with thinking you’ve already solved a problem in your head. You become so eager to see your solution come to life that you rush into implementation, only to discover how many variables and edge cases you hadn’t considered.

Productivity, what is it?

I’ve always been suspicious of measuring productivity as output divided by effort. Lines of code are an obvious measure of output, but they tell us little about what a developer actually learns along the way.

I’m currently studying Software Metrics: A Rigorous and Practical Approach by Norman Fenton and James Bieman. One concept that caught my attention is that external metrics depend not only on the product but also on its environment. Even complexity, for instance, depends partly on the experience of the person reading the code.

This got me thinking about the less visible products of programming: the patterns we internalize, the discipline we develop, and our growing instinct for where bugs hide. None of these shows up in a line count, yet all of them matter.

A week spent writing almost nothing but learning to build programs skeleton-first taught me more than a week spent brute-forcing three exercises. That made me question whether we’re too preoccupied with what we can measure to appreciate what we can’t.

It also brought me to another realization: humility is probably crucial to becoming a good programmer. Prioritizing the work over the appearance of competence, listening to other perspectives, and acknowledging what we don’t know seem like obvious ingredients for progress. Yet I catch myself doing the opposite, and I see the same tendency in others.

Perhaps that’s worth reflecting on. As Dijkstra argued in The Humble Programmer, good programming begins with recognizing the limits of our own minds.

The End

Thanks for passing by,remember the details of the facts now live in their own log so you can skim through when you need them rather than reading past them here. I hope to use this pattern for future blogs I’m also considering splitting chapters into multiple blogs, I noticed this may be necessary for books like CS:APP with dense chapters, I am open to suggestions however so I can shape the blogs in a way that’s more helpfull to you so feel free to reach out. Chapter 2 has the kinds of details that costs you hours later if you skip them, especially the machine-dependent parts.

Keywords are under the title if you want your next rabbit hole as usual. Now go do stuff.

Related posts

Change Log

4 total
  1. Return

    I had to look up that word, by the way. I find the use of big words sometimes an impediment to communication. I try to explain things as I understand them, so anything that may seem oversimplified simply means I found it worth breaking down based on the effort it took me to understand. My preference for lexical accessibility should not be mistaken for a paucity of vocabulary; were ego my editor, these expositions would overflow with sesquipedalian obscurities and labyrinthine circumlocutions, necessitating a permanent Merriam-Webster tab. Alas, in deference to the reader's time and comprehension, I must reluctantly temper my otherwise insatiable appetite for ostentatious eloquence. Yes... I googled those too.

  2. Return

    I went down a rabbit hole on how floats are actually stored. Under IEEE 754, a normalized float is value = (-1)^sign x 1.mantissa x 2^(exponent - bias). A 32-bit float gives 1 sign bit, 8 exponent bits and 23 mantissa bits with a bias of 127; a double gives 1, 11 and 52 with a bias of 1023. The leading 1 is implicit, which is where the extra bit of precision comes from. Subnormals (also called denormals) are the exception: when the exponent field is all zeros, the implicit leading bit is 0 instead of 1 and the value becomes 0.mantissa x 2^(1 - bias). That exists so numbers smaller than the smallest normalized value degrade gradually towards zero instead of snapping to it, at the cost of precision. This is also roughly why floats near zero are dense and floats near the maximum are sparse.

  3. Return

    On the portability point about masks, x & ~077 and x & 0177700 do the same thing on a 16-bit int, but only the first is portable. 0177700 hardcodes an assumption about the width of an int; ~077 says "everything except the low six bits" and stays correct whatever the width turns out to be. The general rule is to write masks in terms of the bits you mean rather than the number that happens to represent them on your machine.

  4. Return

    Pardon the comedic deficiency. In my defence, this abomination was conceived in the peculiar intersection of temporary creative bankruptcy, and an inexplicable surplus of the impulse to be creative instigated by prolonged boredom.

← Back to all posts