Sunil Bojanapally
Sunil Bojanapally

Reputation: 12658

Understanding summation logic

Here is the summation logic which performs addition without using + operator as below,

int add(int a, int b) {
   const char *c=0;
   return &(&c[a])[b];
}

Can anyone make me understand how return statement boils to addition of a & b.

Upvotes: 7

Views: 595

Answers (3)

Theolodis
Theolodis

Reputation: 5102

Ok, it is not as complex as you think, but for sure nothing you should use because it's kind of dirty ;)

c is a pointer to NULL or 0 and you take the offset &0[a], which is exactly a, then you take the offset [b] from &0[a], which is 0+a+b.

And that's all the magic.

Upvotes: 7

doptimusprime
doptimusprime

Reputation: 9413

This is just addition of pointer that leads to addition.

To understand it

 &c[a]  = c + a;

and

 &(&c[a])[b] = &c[a] + b = c + a + b;

When you take &(&c[a])[b], it will give c + a + b. Since c is 0, it is a+b.

In fact to get summation of two integer without + operator, use bitwise operators and the logic that is used in full adder circuit.

Upvotes: 3

unwind
unwind

Reputation: 400029

Just remember that since a[b] is the same as *(a + b), there's an implicit add being done whenever you index an array. That means that &a[b] is a + b since the address-of and dereference operators cancel out.

Then, with c set to 0, we can substitute:

&(&c[a])[b] = &(&*(0 + a))[b] = &(a)[b] = &a[b] = &*(a + b) = a + b

I'm not sure this is well-defined and portable, but I imagine it'll work on most "typical" systems.

Upvotes: 12

Related Questions