2 of 2 syntax highlighting

C++

We expect an operation like addition to be very fast. Many of the other answers simply don't concentrate enough on speed. Here's a solution that uses only bitwise operations, for maximum performance.

#include <iostream>

int add2(int a, int b, int bits) {
  // Usage: specify a and b to add, and required precision in bits (not bytes!)
  int carry  = a & b;
  int result = a ^ b;
  while(bits --> 0) {       // count down to 0 with "downto" operator
    int shift = carry << 1;
    carry = result & shift;
    result ^= shift;
  }
  return result;
}

int main() {
  // Test harness
  std::cout << add2(2, 254, 7) << std::endl;
  return 0;
}