When understanding how primitive operators such as +
, -
, *
and /
are implemented in C, I found the following snippet from an
Almost any modern processor that can run compiled C code will have builtin support for integer addition. The code you posted is a clever way to perform integer addition without executing an integer add opcode, but it is not how integer addition is normally performed. In fact, the function linkage probably uses some form of integer addition to adjust the stack pointer.
The code you posted relies on the observation that when adding x and y, you can decompose it into the bits they have in common and the bits that are unique to one of x or y.
The expression x & y
(bitwise AND) gives the bits common to x and y. The expression x ^ y
(bitwise exclusive OR) gives the bits that are unique to one of x or y.
The sum x + y
can be rewritten as the sum of two times the bits they have in common (since both x and y contribute those bits) plus the bits that are unique to x or y.
(x & y) << 1
is twice the bits they have in common (the left shift by 1 effectively multiplies by two).
x ^ y
is the bits that are unique to one of x or y.
So if we replace x by the first value and y by the second, the sum should be unchanged. You can think of the first value as the carries of the bitwise additions, and the second as the low-order bit of the bitwise additions.
This process continues until x is zero, at which point y holds the sum.