7

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.

Community
  • 1
  • 1
Sunil Bojanapally
  • 12,528
  • 4
  • 33
  • 46

3 Answers3

12

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • 1
    I think it is not portable. What if internal representation NULL pointer is not `0`? – user694733 Nov 08 '13 at 08:19
  • http://stackoverflow.com/questions/7016861/null-pointer-in-c-and-c this may answer your question ;) – Theolodis Nov 08 '13 at 08:38
  • @Theolodis I'm not sure how that is relevant? I was wondering about systems where `NULL` is not numeric address value `0x00000000`, so compiler might replace `const char *c=0;` with `const char *c= (void*)0x0BADC0DE;` during compilation. – user694733 Nov 08 '13 at 09:33
  • @user694733 In C++, the null pointer is defined by the ISO specification (§4.10/1) as `A null pointer constant is an integral constant expression (5.19) rvalue of integer type **that evaluates to zero**.` If you would read what I gave you... ;D – Theolodis Nov 08 '13 at 09:40
  • @Theolodis I did, but that is not what I meant. See this: http://stackoverflow.com/a/2759875/694733 – user694733 Nov 08 '13 at 09:44
  • @user694733 if it evaluates to 0 it doesn't matter what its internal representation is. – Theolodis Nov 08 '13 at 09:49
  • @Theolodis But computation happens at runtime so `c[a]`, would become `0x0BADC0DE + a`, not `0 + a`. – user694733 Nov 08 '13 at 09:54
7

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.

Theolodis
  • 4,977
  • 3
  • 34
  • 53
3

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.

doptimusprime
  • 9,115
  • 6
  • 52
  • 90