Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum (adding 2 numbers ) without plus operator

Tags:

c

Can anyone explain the logic how to add a and b?

#include <stdio.h>

int main()
{
     int a=30000, b=20, sum;
     char *p;
     p = (char *) a;
     sum = (int)&p[b];  //adding a and b!
     printf("%d",sum);
     return 0;
}
like image 689
user1215233 Avatar asked Jul 03 '13 14:07

user1215233


1 Answers

The + is hidden here:

&p[b]

this expression is equivalent to

(p + b)

So we actually have:

(int) &p[b] == (int) ((char *) a)[b]) == (int) ((char *) a + b) == a + b

Note that this technically invokes undefined behavior as (char *) a has to point to an object and pointer arithmetic outside an object or one past the object invokes undefined behavior.

like image 83
ouah Avatar answered Sep 23 '22 05:09

ouah