简体   繁体   English

是否为 C++ 标准中未定义的有符号变量分配了超出范围的值

[英]Is Assign a Value Out of Range to a Signed Var Undefined in C++ Standard

I've been read C++ Primer, it said if I assign a value out of range to a signed var will make the var be undefined, but the result of experiment in Visual C++ compiler is same as unsigned var, it will drop higher bits in binary, is that feature in C++ standard?我已经阅读了 C++ Primer,它说如果我为带符号的 var 分配一个超出范围的值将使 var 未定义,但是 Visual C++ 编译器中的实验结果与 unsigned var 相同,它会在二进制,是 C++ 标准中的功能吗? Visual C++ broke it?视觉C++坏了吗?

The behaviour of integral conversions is defined in C++17 [conv.integral]:积分转换的行为在 C++17 [conv.integral] 中定义:

If the destination type is signed, the value is unchanged if it can be represented in the destination type;如果目标类型是有符号的,则如果它可以在目标类型中表示,则值不变; otherwise, the value is implementation-defined.否则,该值是实现定义的。

There is no undefined behaviour.没有未定义的行为。 Furthermore, results of experiments can never tell you anything because you don't know if you are seeing undefined behaviour or not.此外,实验结果永远不会告诉你任何事情,因为你不知道你是否看到了未定义的行为。 The only reliable method is to check the Standard.唯一可靠的方法是检查标准。 And if the standard says "implementation-defined" then you check your compiler's documentation to see what the definition is.如果标准说“实现定义”,那么您检查编译器的文档以查看定义是什么。


This will probably change in C++20, the new text from the latest standard draft is:这可能会在 C++20 中改变,最新标准草案的新文本是:

the result is the unique value of the destination type that is congruent to the source integer modulo 2 N , where N is the width of the destination type.结果是与源 integer 模 2 N一致的目标类型的唯一值,其中 N 是目标类型的宽度。

which is formal language for "discard high bits in 2's complement representation".这是“丢弃 2 的补码表示中的高位”的形式语言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM