为什么长时间表现得像C中的int?

时间:2015-02-09 01:42:18

标签: c

我跟着k& r C书,我偶然发现了奇怪的事情2-1(确定你的机器上的短,int和长的最大尺寸)。 我为它编写了这段代码:

#include <stdio.h>

int main()
{
    long a;
    long lasta;
    int b , lastb;
    short int c, lastc;

    lasta = lastb = lastc = 1;
    a = b = c = 2;
    while (a || b || c) {
        printf("lasta = %d\n", lasta); //for debugging
        a = a * 2;
        b = b * 2;
        c = c * 2;
        lasta = lasta * 2;
        lastb = lastb * 2;
        lastc = lastc * 2;
        if (a < lasta) {
            printf("%d\n", lasta * 2 - 1);
            a = lasta = 0;
        }
        if (b < lastb) {
            printf("%d\n", lastb * 2 - 1);      
            b = lastb = 0;
        }
            if (c < lastc) {
            printf("%d\n", lastc * 2 - 1);      
            c = lastc = 0;      
        }
    }
}

我得到一个奇怪的错误,它似乎适用于短和int,但不长。我觉得它的行为好像是lasta是一个普通的int。这是输出:

lasta = 1
lasta = 2
lasta = 4
lasta = 8
lasta = 16
lasta = 32
lasta = 64
lasta = 128
lasta = 256
lasta = 512
lasta = 1024
lasta = 2048
lasta = 4096
lasta = 8192
32767
lasta = 16384
lasta = 32768
lasta = 65536
lasta = 131072
lasta = 262144
lasta = 524288
lasta = 1048576
lasta = 2097152
lasta = 4194304
lasta = 8388608
lasta = 16777216
lasta = 33554432
lasta = 67108864
lasta = 134217728
lasta = 268435456
lasta = 536870912
2147483647
lasta = 1073741824
lasta = -2147483648
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
lasta = 0
-1

我意识到我只能通过查看a的值来得到答案,但我想知道这里发生了什么

1 个答案:

答案 0 :(得分:3)

printf with %d意味着它认为它是一个int。

尝试%lu,它会打印无符号长