Skip to content

Latest commit

 

History

History
37 lines (28 loc) · 833 Bytes

bug542.md

File metadata and controls

37 lines (28 loc) · 833 Bytes

指定长度的整形数

找Bug

下面这段代码会输出什么?为什么?

#include <stdio.h>

struct { int bit:1; } s;

bool f()
{
    if( s.bit > 0 ) return true;
    else return false;
}

int main()
{
    s.bit = 1;
    if( f() ) printf( "the bit is ON\n" );
    else printf( "the bit is OFF\n" );
    return 0;
}

说明

'int' 表示它是一个带符号的整数。对于带符号的整数,最左边的位将用作 +/- 符号。 如果在 1 位字段中存储 1: 最左边的位为 1,因此系统会将其值视为负数。 系统使用2的补码方法来处理负值。
因此,存储的数据为1。1的2的补码也为1(负数),此时这个int的值就是-1。f()的返回值也就是false。