是否有 if 语句可以计算的标准化最大变量二进制宽度

Is there a standardized maximum variable binary width that an if statement can evaluate?

本文关键字:变量 二进制 标准化 if 语句 计算 是否      更新时间:2023-10-16

是 if 语句可以计算特定于实现的最大可变宽度。或者,编译器是否可以强制将变量上的强制转换为另一种类型(如布尔值),以便由 if 语句计算。请考虑下面的代码以及我计算机上的输出。我问是因为我想可靠地分发一个库,用于许多不同的机器,包括 arm、mips、amd86、x86 等。请注意,我知道本机整数类型并不总是达到 64/32/16 位宽度。

此外,如果它被定义,那么它是如何定义的?

法典:

#include <iostream>
#include <cstdint>
#include <bitset>
int main() {
// Initialises variables with a single binary 1 in the left most place.
uint8_t eight_bit = (~0) << (8 - 1);
uint16_t sixteen_bit = (~0) << (16 - 1);
uint32_t thirty_two_bit = (~0) << (32 - 1);
uint64_t sixty_four_bit = (~0) << (64 - 1);

std::cout << "The 8 bit integer is equal to: " 
    << std::bitset<8>(eight_bit) << "n";
std::cout << "The 16 bit integer is equal to: " 
    << std::bitset<16>(sixteen_bit) << "n";
std::cout << "The 32 bit integer is equal to: " 
    << std::bitset<32>(thirty_two_bit) << "n";
std::cout << "The 64 bit integer is equal to: " 
    << std::bitset<64>(sixty_four_bit) << "n";

if (eight_bit)      
    std::cout << "8 bit variable considered true." << "n";
if (sixteen_bit)    
    std::cout << "16 bit variable considered true." << "n";
if (thirty_two_bit) 
    std::cout << "32 bit variable considered true." << "n";
if (sixty_four_bit) 
    std::cout << "64 bit variable considered true." << "n";
return 0;
}

输出:

The 8 bit integer is equal to: 10000000
The 16 bit integer is equal to: 1000000000000000
The 32 bit integer is equal to: 10000000000000000000000000000000
The 64 bit integer is equal to: 1000000000000000000000000000000000000000000000000000000000000000
8 bit variable considered true.
16 bit variable considered true.
32 bit variable considered true.
64 bit variable considered true.

if(X) 的定义是,它的行为就像有一个由这个定义创建的临时

bool temp(X);

然后 iff temp true,测试成功。 如果该声明格式不正确,则if语句格式不正确。

从整数类型到 bool 的转换定义为零给出false,其他所有内容都给出true

(需要明确的是,您的问题的答案是,任何隐式转换为bool的类型都可以通过if语句进行评估)。


铌。 您的问题中的(~0) << (8 - 1);等会导致未定义的行为。非正式地说,将1左移到符号位是未定义的(这意味着负数的所有左移都是未定义的)。

此外,如果您有 32 位整数,(~0) << (64 - 1);会导致 UB 由于移位大于类型的宽度。

为避免这种情况,请从 1ULL 而不是 ~0 开始,或者做类似 uint64_t x = INT64_MIN; .(使用后一种方法,您可以使用模板通过std::numeric_limits查找值)。

C++标准 (C++11) 定义了多达 64 位整数类型:

http://en.cppreference.com/w/cpp/types/integer

但是,某些实现最高可达 128 位。

https://msdn.microsoft.com/en-us/library/cc953fe1.aspx

据推测,特定的实现可以定义自己的扩展以任意大。

因此,如果您想坚持使用便携式C++标准类型,请坚持使用 C++ 规范中定义的 64 位及以下类型。 如果本机大小较小,则标准编译器将通过组合较小的本机字来提供支持较大大小(可能会降低性能)的实现。 (例如,在 32 位平台上从 2 个 32 位字创建一个 64 位整数。

如果你真的想问"我如何找到我的平台上最大的原生大小?"这是一个不同的问题。