回答編集履歴

1

具体的な仕様を引用

2021/05/04 04:24

投稿

SaitoAtsushi
SaitoAtsushi

スコア5461

test CHANGED
@@ -1 +1,31 @@
1
1
  C# には明るくないので確信を持って言えません (常識的には維持されるでしょう) が、 C と C++ では変換後の型で表現可能な値であればその値が維持されることは言語仕様が保証しています。
2
+
3
+
4
+
5
+ 具体的に、 C17 の 6.3.1.3 にはこう書かれています。
6
+
7
+
8
+
9
+ > When a value with integer type is converted to another integer type other than `_Bool`, if the value can be represented by the new type, it is unchanged.
10
+
11
+ > (整数型の値が `_Bool` 以外の別の整数型に変換されると、新しい型で値を表すことができれば変更されません。)
12
+
13
+ > Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
14
+
15
+ > (そうではなく新しい型が符号なしである場合、値は新しい型の範囲内になるまで、新しい型で表すことができる最大値を繰り返し追加または減算することによって値を変換します。)
16
+
17
+
18
+
19
+ C++17 の 7.8.3 にはこうあります。
20
+
21
+
22
+
23
+ > 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.
24
+
25
+
26
+
27
+ > (変換先の型が符号付きである場合、変換先の型で表すことができれば値は変更されません。 それ以外の場合には値は処理系定義です。)
28
+
29
+
30
+
31
+ ちなみに C++20 以降では負数の表現が二の補数とすることになりました (従来は一の補数や、符号と絶対値の組で表す表現も認められていました) ので、変換先の型が符号付きの場合にその表現範囲内で表せなくても変換後の値について保証されるように変更されています。