Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this how the + operator is implemented in C?

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?

like image 849
nalzok Avatar asked Feb 26 '16 13:02

nalzok


People also ask

What is the operator in C?

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.

How many types of operators are there in C?

C/C++ has many built-in operators and can be classified into 6 types: Arithmetic Operators. Relational Operators. Logical Operators.

What does &= mean in C?

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.


1 Answers

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.

like image 80
orlp Avatar answered Sep 28 '22 09:09

orlp