gpt4 book ai didi

c++ - unsigned long 的类型不同于 Windows 上的 uint32_t 和 uint64_t (VS2010)

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:21:15 26 4
gpt4 key购买 nike

在 Windows 7、32 位的 Visual Studio 2010 上,unsigned long 似乎是与 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)

当然假设 long 不超过 64 位。

然而,在 Windows 上,我感到莫名其妙

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

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

最佳答案

There are two distinct 32-bit, unsigned types

是的,有。 intlong都用32位表示。

Is this allowed by the C++ standard?

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

There are five standard signed integer types : signed char, short int, int, long int, and long long int. In this list, each type provides at least as much storage as those preceding it in the list.

For each of the standard signed integer types, there exists a corresponding (but different) standard unsigned integer type...each of which occupies the same amount of storage and has the same alignment requirements as the corresponding signed integer type

请注意,尽管 intlong 由相同的位数表示,但它们仍然是不同的类型(因此,例如,它们被区别对待在重载决议期间)。

关于c++ - unsigned long 的类型不同于 Windows 上的 uint32_t 和 uint64_t (VS2010),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11611467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com