c/c++语言开发共享为什么以下代码的输出是-1和-2?

为什么下面代码的输出是-1和-2,它应该是1和2,对吧?

在以下结构的64位服务器大小上也是4字节,它应该是8字节对吗?

#include struct st { int a:1; int b:2; }; main() { struct st obj={1,2}; printf("a = %dnb = %dn",obj.a,obj.b); printf("Size of struct = %dn",sizeof(obj)); } 

    编译启用的所有警告,并阅读编译器所说的内容:

     Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c main.c:7:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int] main() ^ main.c:9:26: warning: implicit truncation from 'int' to bitfield changes value from 2 to -2 [-Wbitfield-constant-conversion] struct st obj={1,2}; ^ main.c:11:40: warning: format specifies type 'int' but the argument has type 'unsigned long' [-Wformat] printf("Size of struct = %dn",sizeof(obj)); ~~ ^~~~~~~~~~~ %lu 3 warnings generated. 

    回想起那个

    带符号的1位变量只能包含两个值,即-1和0

    正如你在这个答案中看到的那样。

    所以如果你改用这个结构:

     struct st { int a:2; int b:3; }; 

    你会得到所需的输出。


    这个答案也给出了一个很好的解释。

      以上就是c/c++开发分享为什么以下代码的输出是-1和-2?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/549212.html

      (0)
      上一篇 2021年1月13日
      下一篇 2021年1月13日

      精彩推荐