sum (adding 2 numbers ) without plus operator

后端 未结 9 680
借酒劲吻你
借酒劲吻你 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:22

    1. p is made a pointer to char

    2. a is converted to a pointer to char, thus making p point to memory with address a

    3. Then the subscript operator is used to get to an object at an offset of b beyond the address pointed to by p. b is 20 and p+20=30020 . Then the address-of operator is used on the resulting object to convert the address back to int, and you've got the effect of a+b

    The below comments might be easier to follow:

    #include 
    
    int main()
    {
         int a=30000, b=20, sum;
         char *p; //1. p is a pointer to char
         p = (char *) a; //2. a is converted to a pointer to char and p points to memory with address a (30000)
         sum = (int)&p[b];  //3. p[b] is the b-th (20-th) element from address of p. So the address of the result of that is equivalent to a+b
         printf("%d",sum);
         return 0;
    }
    

    Reference: here

提交回复
热议问题