I'm confused with a output . So I'm expecting explaination For my output

主宰稳场 提交于 2019-12-13 11:30:35

问题


   #include <stdio.h>
    {
        char num = 127;
        num = num + 1;
        printf("%d", num);
      return 0;
     }

Output is : -128 should I add output shot


回答1:


char is a that, on most systems, takes 1 byte (8 bits). Your implementation seems to have char represent a signed type, however on other implementations it could be unsigned. The maximum value for a signed type is 2^(n-1)-1, where n is the number of bits. So the maximum value of char is 2^(8-1)-1=2^7-1=128-1=127. The minimum value is actually -2^(n-1). This means the minimun value is -128. When you add something that goes over the maximum value, it overflows and loops back to the minimum value. Hence, 127+1=-128 if you are doing char arithmetic.

You never use char for arithmetic. Use signed char or unsigned char instead. If you replace your char with unsigned char the program would print 128 as expected. Just note that the overflow can still happen (unsigned types have a range from 0 to 2^n-1, so unsigned char overflows if you add 1 to 255, giving you 0).



来源:https://stackoverflow.com/questions/57935968/im-confused-with-a-output-so-im-expecting-explaination-for-my-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!