Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding summation logic

Tags:

c

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.

like image 465
Sunil Bojanapally Avatar asked Nov 08 '13 08:11

Sunil Bojanapally


2 Answers

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.

like image 132
unwind Avatar answered Sep 28 '22 09:09

unwind


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.

like image 24
Theolodis Avatar answered Sep 28 '22 08:09

Theolodis