新人Y子のプログラミングのお部屋21

オーバーフローの実験


[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]char型は、-128〜127まで表せるのですよね?
では、その範囲を超えた場合どうなるのですか?

[/speech_bubble]
[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]それでは、次のようなプログラムをつくって実験してみましょう。

[/speech_bubble]

[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]このプログラムは何をしているのですか?
[/speech_bubble]

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]char型の最大値127に、1を加えたらどうなるかを確認するプログラムです。
では、「Coding Ground」で確かめてみましょう。
[/speech_bubble]

[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]はい、Coding Groundに、ソースコードを入力しました。


[/speech_bubble]

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]では、「Execute」を押して、実行してみてください[/speech_bubble]

[speech_bubble type="std" subtype="R1" icon="sanoyu-hatena.png" name="新人Y子"]実行しました。
あれ?エラーは出ないのですね。
そして、実行結果も「-128」となっていて、実際の答えとかなり違うのですが、なぜでしょう?


[/speech_bubble]

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]はい、これが「オーバーフロー」した状態です。

[/speech_bubble]
[speech_bubble type="std" subtype="R1" icon="sanoyu-hatena.png" name="新人Y子"]オーバーフローすると、なぜプラスだったものがマイナスになるのでしょうか?
[/speech_bubble]

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]では、確認してみましょう。
足す前の「127」は、2進数で「01111111」です。
これから、1を足してみてください。
[/speech_bubble]

[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]「01111111」+1は、繰り上がりが続いて「10000000」ですね。
[/speech_bubble]

[speech_bubble type="std" subtype="R1" icon="sanoyu-bikkuri.png" name="新人Y子"]あっ!
最上位の符号ビットが変わってしまいました。
[/speech_bubble]

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]そういう事ですね。
計算した結果の「10000000」は、char型の2の補数表現で、-128ですね。

[/speech_bubble]
[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]だから、「-128」と表示されたのですね。
それにしても、オーバーフローすると、期待した値と大きく違う結果になってしまうのですね。
[/speech_bubble]
[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]そうなんです。オーバーフローは、バグの原因にもなります。

[/speech_bubble]
[speech_bubble type="std" subtype="R1" icon="sanoyu-hatena.png" name="新人Y子"]では、オーバーフローしないようにプログラムをつくるにはどうしたらいいですか?
[/speech_bubble]

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]プログラムをつくる前に、値の範囲を見積もることです。
例えば、テストの点(100点満点)を記憶するには、char型使用で十分ですが、
マイナンバー(12桁)のような大きな値を扱う場合は、long型を使用するなどです。
[/speech_bubble]

[speech_bubble type="std" subtype="R1" icon="sanoyu-bikkuri.png" name="新人Y子"]そうやって、オーバーフローを回避するわけですね。
[/speech_bubble]

[speech_bubble type="std" subtype="R1" icon="techtrageman-normal.png" name="テクトレージマン"]次回に続く[/speech_bubble]

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

目次