When understanding how primitive operators such as +
, -
, *
and /
are implemented in C, I found the following snippet from an interesting answer.
// replaces the + operator int add(int x, int y) { while(x) { int t = (x & y) <<1; y ^= x; x = t; } return y; }
It seems that this function demonstrates how +
actually works in the background. However, it's too confusing for me to understand it. I believed that such operations are done using assembly directives generated by the compiler for a long time!
Is the +
operator implemented as the code posted on MOST implementations? Does this take advantage of two's complement or other implementation-dependent features?
An operator is a symbol that operates on a value or a variable. For example: + is an operator to perform addition. C has a wide range of operators to perform various operations.
C/C++ has many built-in operators and can be classified into 6 types: Arithmetic Operators. Relational Operators. Logical Operators.
It means to perform a bitwise operation with the values on the left and right-hand side, and then assign the result to the variable on the left, so a bit of a short form.
To be pedantic, the C specification does not specify how addition is implemented.
But to be realistic, the +
operator on integer types smaller than or equal to the word size of your CPU get translated directly into an addition instruction for the CPU, and larger integer types get translated into multiple addition instructions with some extra bits to handle overflow.
The CPU internally uses logic circuits to implement the addition, and does not use loops, bitshifts, or anything that has a close resemblance to how C works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With