为什么下面代码的输出是-1和-2? [英] Why output of the below code is -1 and -2?

查看:33
本文介绍了为什么下面代码的输出是-1和-2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why output of the below code is -1 and -2, It should be 1 and 2, Right?

同样在 64 位服务器上,以下结构的大小是 4 Bytes,应该是 8 Bytes 吧?

Also on a 64 bit server size of the below structure is 4 Bytes, It should be 8 Bytes right?

#include<stdio.h>
struct st
{
        int a:1;
        int b:2;
};
main()
{
        struct st obj={1,2};
        printf("a = %d\nb = %d\n",obj.a,obj.b);
        printf("Size of struct = %d\n",sizeof(obj));
}

推荐答案

在启用所有警告的情况下编译,并阅读您的编译器所说的内容:

Compile with all the warnings enabled, and read what your compiler says:

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 = %d\n",sizeof(obj));
                                 ~~    ^~~~~~~~~~~
                                 %lu
3 warnings generated.

回忆一下

一个带符号的 1 位变量只能保存两个值,-1 和 0

a signed 1 bit variable can hold only two values, -1 and 0

正如您在此答案中所见.

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

So if you use this struct instead:

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

您将获得所需的输出.

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

This answer gives a nice explanation as well.

这篇关于为什么下面代码的输出是-1和-2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆