无符号长整数是否固定为int(4字节)范围,如果是这样,为什么它在内存中是8个字节?

时间:2013-04-26 17:51:38

标签: c++ types sizeof unsigned

编辑:愚蠢的问题,我忽略了格式标识符。

我有一个程序抓住一些无符号类型的大小及其最大值。这引起了我的注意,甚至认为unsigned long long是8个字节的事实,它的范围似乎固定为4字节范围。 (char是保证的8位字节)

问题
我了解unsigned long long仅由标准定义为至少足以容纳int(或者更确切地说> = long int> = int传递。但是,为什么它使用8字节的内存而不是与int相同的大小,如果它也限制在4字节的范围内呢?

unsigned char:             255         1*sizeof(char)           
unsigned short:            65535       2*sizeof(char)        
unsigned short int:        65535       2*sizeof(char)       
unsigned int:              4294967295  4*sizeof(char)            
unsigned long int:         4294967295  4*sizeof(char)            
unsigned long long int:    4294967295  8*sizeof(char)  //range[0..18446744073709551615]       
unsigned long:             4294967295  4*sizeof(char)            
unsigned long long:        4294967295  8*sizeof(char)  //range[0..18446744073709551615]

以下是我使用的来源:

#include <iostream>
#include <cstdio>

int main(void){

    std::cout << "Type sizes: (multiples of char)"<< std::endl << "char: " << sizeof(char) << std::endl <<\
    "short: " << sizeof() << std::endl <<\
    "short int: " << sizeof(short int) << std::endl << std::endl <<\
    "int: " << sizeof(int) << std::endl <<\
    "long int: " << sizeof(long int) << std::endl <<\
    "long long int: " << sizeof(long long int) << std::endl << std::endl <<\
    "long: " << sizeof(long) << std::endl <<\
    "long long: " << sizeof(long long) << std::endl << std::endl <<\
    "float: " << sizeof(float) << std::endl <<\
    "double: " << sizeof(double) << std::endl;

    unsigned char c = -1;
    unsigned short s1 = -1;
    unsigned short int s2 = -1;

    unsigned int i = -1;
    unsigned long int i1 = -1;
    unsigned long long int i2 = -1;

    unsigned long l = -1;
    unsigned long long l1 = -1;

    printf("\
            \nUnsigned Max:     \n\
            \nchar:             %u\
            \nshort:            %u\
            \nshort int:        %u\
            \nint:              %u\
            \nlong int:         %u\
            \nlong long int:    %u\
            \nlong:             %u\
            \nlong long:        %u\
            ", c, s1, s2, i, i1, i2, l, l1);

    return 0;
}

1 个答案:

答案 0 :(得分:1)

您使用printf的错误标记,值实际上是正常的,但printf未正确显示它们。对%llu尝试unsigned long long

有关printf(旗帜)的更多信息:http://www.cplusplus.com/reference/cstdio/printf/