消息关闭
    暂无新消息!

对于C/C++,不同的编译器对数据类型的长度有着不同的规定。部分编译器规定int与long都占4个字节,那么在这种情况下,long和int有什么区别呢?应该在什么情况下使用long与int呢?

ISO C++ 标准中只规定了long的长度 不小于 int,那么在它们长度相同时,这两种数据类型同时存在的意义又是什么呢?

初学者诚心向大神请教一二


3个回答

︿ 2

是这样的,其实不光是 longint 其实也只保证了下限是 16 位(虽然你大多看到的是 32 位)

因为 C 适配的机器确实太广泛了,所以很难去直接限定一个类型固定占多少位

所以规范只限制了:

char <= short <= int <= long <= long long

char      >= 8 bits
short     >= 16 bits
int       >= 16 bits
long      >= 32 bits
long long >= 64 bits
︿ 1

What's the standard guarantees is sizeof(int) <= sizeof(long).

In in a production environment(especially cross-platform), we will use fixed width integer types.

@int64ago sizeof(int) is not always >= 16, char can just be used as short short int(not actually exists) and int8_t is just typedef to char in platforms where 1 byte == 8bits

No matter what platforms, sizeof(intX_t) guarantees X bits(equal to $frac{X}{8}$ bytes at most platforms).

You can try:

#include "stdafx.h"
#include <cinttypes>
#include <iostream>
int main()
{
    std::cout
        << "sizeof(int8_t) = " << sizeof(int8_t) << std::endl
        << "sizeof(int16_t) = " << sizeof(int16_t) << std::endl
        << "sizeof(int32_t) = " << sizeof(int32_t) << std::endl
        << "sizeof(int64_t) = " << sizeof(int64_t) << std::endl;
}

Here is my try: