无符号长的类型与Windows(VS2010)上的uint32_t和uint64_t不同

Type of unsigned long is different from uint32_t and uint64_t on Windows (VS2010)

本文关键字:上的 uint32 不同 uint64 VS2010 类型 Windows 无符号      更新时间:2023-10-16

在Windows 7下的Visual Studio 2010上,32位无符号长似乎是与uint32_t和uint64_t不同的类型。参见以下测试程序:

#include <stdint.h>
#include <stdio.h>
template<class T, class U>
struct is_same_type
{
    static const bool value = false;
};
template<class T>
struct is_same_type<T, T>
{
    static const bool value = true;
};
#define TO_STRING(arg)        TO_STRING_IMPL(arg)
#define TO_STRING_IMPL(arg)   #arg
#define PRINT_SAME_TYPE(type1, type2) printf("%s (size=%d) %s %s (size=%d)n", 
    TO_STRING(type1), int(sizeof(type1)), 
    is_same_type<type1, type2>::value ? "==" : "!=", 
    TO_STRING(type2), int(sizeof(type2)))

int main(int /*argc*/, const char* /*argv*/[])
{
    PRINT_SAME_TYPE(uint32_t, unsigned long);
    PRINT_SAME_TYPE(uint64_t, unsigned long);
    return 0;
}

我希望它能打印

uint32_t (size=4) != unsigned long (size=8)
uint64_t (size=8) == unsigned long (size=8)

(我在x86_64 Linux上获得)或

uint32_t (size=4) == unsigned long (size=4)
uint64_t (size=8) != unsigned long (size=4)

当然,假设该长度不长于64位。

然而,在Windows上,我得到了令人困惑的

uint32_t (size=4) != unsigned long (size=4)
uint64_t (size=8) != unsigned long (size=4)

这意味着存在两种不同的32位无符号类型。C++标准允许这样做吗?或者这是Visual C++编译器中的一个错误?

有两种不同的32位无符号类型

是的,有。CCD_ 1和CCD_。

C++标准允许这样做吗?

是的。规范规定(C++11§3.9.1[基本.基本]/2):

有五种标准的有符号整数类型:signed charshort intintlong intlong long int。在该列表中,每种类型提供的存储量至少与列表中其前面的类型一样多

对于每个标准的有符号整数类型,都存在一个对应的(但不同的)标准无符号整数类型。。。每个占用相同的存储量,并且具有与对应的带符号整数类型相同的对准要求

请注意,尽管intlong由相同数量的比特表示,但它们仍然是不同的类型(因此,例如,在过载解析期间,它们被不同地对待)。