是否有 if 语句可以计算的标准化最大变量二进制宽度
Is there a standardized maximum variable binary width that an if statement can evaluate?
是 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 位整数。
如果你真的想问"我如何找到我的平台上最大的原生大小?"这是一个不同的问题。
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 在 C++ 中将双精度变量写入二进制文件
- 从二进制流中读取时,将双精度变量的地址转换为 char* 意味着什么?
- 没有变量声明为函数,但错误:二进制表达式的操作数无效
- 在类中添加新的成员变量会影响二进制兼容性
- 如何将变量二进制数据(作为字符串)转换为字节数组
- 从二进制缓冲区初始化变量的正确方法是什么
- 可以添加静态变量破坏 Linux 上的二进制兼容性
- 各种数据类型的变量如何存储在C++(本机)二进制文件中
- 是否有 if 语句可以计算的标准化最大变量二进制宽度
- 读取二进制文件时使用的变量的问题
- 程序从存储在自身中的变量而不是从二进制文件中读取
- 对于二进制数据,哪个性能更高:将整个对象写入文件或分隔变量(无对象)
- 字符串流变量不显示在二进制代码中
- 如何在启动时从FastCGI c++二进制文件中获取环境变量
- 将不同类型的变量写入二进制文件,然后将其读入类变量,会得到错误的值
- 最终二进制大小:constexpr变量与constexpr函数
- 字符串与二进制文件,用于在文件格式中存储变量
- 如何在c++上将分类数据转换为二进制变量
- 二进制到十进制递归-没有全局变量