Macros Galore!

In last week’s Lesson, I demonstrated how macros can save time, effectively replacing one-line functions in your code. One place I’ve used macros in my own code is when performing binary math operations.

Binary math isn’t anything you need to do in the C language. C is capable because it’s a mid-level language, but it also includes mathematical operators and functions that operate at a high level. Back in my assembly language days, however, binary math was something you had to program.

The processors back in the old days lacked complex mathematic instructions. For example, if you wanted to multiply a value by six you’d perform these steps:

  1. Shift the value left one notch, doubling it. Save that value.
  2. Add the new value to itself twice.

In C, you express this operation on the value in variable a as follows:

a <<= 1;
a += a + a;

The first statement doubles the value in a, so 5 becomes 10.

The second statement adds 10 to itself once for 20 and to itself again for 30: 5 * 6 = 30.

These statements represent molecules in binary arithmetic, performing simple functions that carry out basic math. They’re ideal for inclusion in your code as macros. To wit:

#define BYTWO(a) a<<1

The BYTWO() macro multiplies the value of variable a by two, doubling it. The macro needs an lvalue, so the result must be assigned as in:

x = BYTWO(4);

This macro triples a value:

#define BYTHREE(a) a+(a<<1)

The value of variable a is added to its double, which must also be assigned as in:

x = BYTHREE(4);

Of course, all these macros are silly given that C features math operators that let you multiply any value by any other. At the microscopic level, bit shifting for multiplication is faster than higher-order operations, though at today’s processor speeds the performance boost you see is minimal. Still, I think it’s fun to play with such macros and concoct methods of performing math at the binary level.

Here’s another macro I’ve used in my code:

#define NEWLINE() putchar('\n')

The NEWLINE() macro outputs the newline character, which helps clean up program output. It’s handy.

Creating macros can be fun, but avoid their over-use just to be cute. It’s possible (and I’ve seen it done) to obfuscate C code to make it look like a completely different language. While such efforts can be the foundation of curiosity or discussion, they detract from the bigger picture goal of keeping your code readable.

Leave a Reply