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
.
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.
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.
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