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

このプログラムの出力結果は何でしょう?の続きです。
[speech_bubble type=”std” subtype=”R1″ icon=”sanoyu-normal.png” name=”新人Y子”]このプログラムの出力結果は、
-222 + 333 = 111
で、合っていますでしょうか?
[/speech_bubble]
[speech_bubble type=”std” subtype=”L1″ icon=”itokuma-normal.png” name=”しげちゃん先生”]正解です!
実際に「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=”しげちゃん先生”]はい。[/speech_bubble]

[speech_bubble type=”std” subtype=”R1″ icon=”sanoyu-normal.png” name=”新人Y子”]入力しましたので、「Execute」ボタンを押しますね。

[/speech_bubble]

 
 
[speech_bubble type=”std” subtype=”R1″ icon=”sanoyu-hatena.png” name=”新人Y子”]あれ???
「-222 + 333 = -645632542」と出力されました。
私の回答「-222 + 333 = 111」と、ずいぶん違うのですが・・・
[/speech_bubble]
[speech_bubble type=”std” subtype=”L1″ icon=”itokuma-normal.png” name=”しげちゃん先生”]「-222 + 333 = 111」が正解です。
[/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=”しげちゃん先生”]ソースコードに、入力ミスがあるためです。
確認してみてください。
[/speech_bubble]
[speech_bubble type=”std” subtype=”R1″ icon=”sanoyu-bikkuri.png” name=”新人Y子”]あっ!
7行目の引数が1つ少なかったようです。
「%d」が3つあるにも関わらず、対応する引数を2つしか指定しなかった事が原因ですね。
[/speech_bubble]
 
[speech_bubble type=”std” subtype=”R1″ icon=”sanoyu-normal.png” name=”新人Y子”]でもなぜ、間違っているのに、正常にコンパイルできて(*1)、動作までしたのでしょう? 
[/speech_bubble]
[speech_bubble type=”std” subtype=”L1″ icon=”itokuma-normal.png” name=”しげちゃん先生”]よい疑問ですね。
今回のように、書式の数と引数の数が一致してない典型的なソースコードの入力ミスでも、printf関数は、ミスを疑わず正直に動作するんです。
[/speech_bubble]
[speech_bubble type=”std” subtype=”R1″ icon=”sanoyu-normal.png” name=”新人Y子”]この変な値「-645632542」はどこからきているのでしょう?
[/speech_bubble]
[speech_bubble type=”std” subtype=”L1″ icon=”itokuma-normal.png” name=”しげちゃん先生”]printf関数は、今回の場合は、「%d」が3つありますので、1つ目の「%d」2つ目の「%d」、3つ目の「%d」に対応する引数が正しく設定されているものと信じて動くので、この3つ目の変数が本来存在するはずのメモリー上のごみデータを拾い、不定な値が出力されているのです。
[/speech_bubble]
[speech_bubble type=”std” subtype=”R1″ icon=”sanoyu-normal.png” name=”新人Y子”]メモリー上のごみを拾うのですか?メモリー上のごみって、必ず「-645632542」なのでしょうか?
そもそも、メモリーとは何でしょう?
[/speech_bubble]
[speech_bubble type=”std” subtype=”L1″ icon=”itokuma-normal.png” name=”しげちゃん先生”]メモリーとは、主記憶装置のことで、プログラムやデータが入る場所です。メモリーの状態は、絶えず入れ替わっていますので、ごみの値が「-645632542」であるとは限りません。
[/speech_bubble]
[speech_bubble type=”std” subtype=”R1″ icon=”sanoyu-normal.png” name=”新人Y子”]なるほど。分かりました。
では、ソースコードを修正して再度実行しますね。
[/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]

(*1) コンパイルオプションによっては、printfの書式と引数の関係を分析して、コンパイル時に見つけることも可能です。
今回はprintf関数の機能説明のため解説は省略させていただきます。

でた

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

この記事を書いた人

目次