C ++语言标准说明了static_cast如何处理减小整数的大小? [英] What does the C++ language standard say about how static_cast handles reducing the size of an integer?

查看:181
本文介绍了C ++语言标准说明了static_cast如何处理减小整数的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道C ++语言标准为以下情况指定的规则:

I would like to know the rules specified by the C++ language standard for situations like:

long x = 200;
short y = static_cast<short>(x);

保证为 y 标准是否由实施决定?

Is y guaranteed to be 200, or does the standard leave this up to the implementation to decide? How well do various compilers adhere to the standard?

推荐答案

在这种情况下, static_cast< / code>是一个'显式类型转换。该标准对4.7 / 3积分转换中的积分转换进行了说明:

In this case the static_cast<> is an 'explicit type conversion. the standard has this to say about integral conversions in 4.7/3 "Integral conversions":


如果目标类型是带符号的,不变,如果它可以表示在目的地类型(和位字段宽度);

If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.

由于 short 能够保持值 200 short 必须至少为16位),那么对于您的具体示例,是的。

Since short is guaranteed to be able to hold the value 200 (short must be at least 16 bits), then for your specific example the answer is yes.

各种编译器坚持这种行为很好 - 这是一种方式,从ANSI之前的C天,这么多的代码取决于行为,编译器供应商似乎不愿意发出关于截断可能性的警告。

Various compilers adhere to this behavior quite well - it's been that way since the pre-ANSI days of C, and so much code depends on the behavior that compiler vendors seem reluctant to even issue warnings about the possibility of truncation.

这篇关于C ++语言标准说明了static_cast如何处理减小整数的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆