sum (adding 2 numbers ) without plus operator

后端 未结 9 659
借酒劲吻你
借酒劲吻你 2021-02-05 20:42

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

#include 

int main()
{
     int a=30000, b=20, sum;
     char *p;
             


        
9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-05 21:32

    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.

提交回复
热议问题