[Phillip] wanted to play with the C preprocessor. He decided to do that by creating a 4 bit full adder. We know this is pretty useless in everyday life, but it was a great learning experience. The beauty of this adder is right at the start. [Phillip] defines truth tables for XOR and AND. He’s able to then create strings that reference these truth tables.
For example: the first line of [Phillip's] AND table is #define AND_00 0. If the preprocessor concatenates strings that equal “AND_00” they will then be converted to 0. This is the groundwork for the half adder .
The next step is the operational logic, which of course falls upon macros:
/* Full adder macros */ /* Out = (A ^ B) ^ cin */ #define FULL_ADD_OUT( a, b, cin ) \ XOR( XOR( a, b ), cin ) /* Carry_out = (A & B) ^ (Carry_in & (A ^ B)) */ /* The standard adder uses OR for the last 'gate' - this can safely be changed to XOR, which has been done here to avoid defining an OR operator */ #define FULL_ADD_CARRY( a, b, cin ) \ XOR( AND( XOR( a, b ), cin ), AND( a, b ) )
This preprocessor code above defines the traditional full adder logic in terms of AND and XOR. That’s really all there is to the logic of the adder itself. The next step is to chain the adders together for four bits. More bits are possible, but the code would get rather messy.
The last bit of magic [Phillip] performed was to convert decimal numbers to binary. He used the same concatenation trick as he did with XOR and AND to make this happen. The end result is a program that can take two numbers as preprocessor options, and compile a binary that will always add those same two numbers when it is run. Like we said – not very useful itself, but a great way to learn some tricks with the C preprocessor that definitely will come in handy down the road.