Don\’t Rely on Undefined Behavior

C++ Primer 4/e 又有一個很好的建議了:『

Programs that use undefined behavior are in error. If they work, it is only by coincidence. Undefined behavior results from a program error that the compiler cannot detect or from an error that would be too much trouble to detect.

Unfortunately, programs that contain undefined behavior can appear to execute correctly in some circumstances and/or on one compiler. There is no guarantee that the same program, compiled under a different compiler or even a subsequent release of the current compiler, will continue to run correctly. Nor is there any guarantee that what works with one set of inputs will work with another.

Programs should not (knowingly) rely on undefined behavior. Similarly, programs usually should not rely on machine-dependent behavior, such as assuming that the size of an int is a fixed and known value. Such programs are said to be nonportable. When the program is moved to another machine, any code that relies on machine-dependent behavior may have to be found and corrected. Tracking down these sorts of problems in previously working programs is, mildly put, a profoundly unpleasant task.』

中文版的是這樣說:『程式如果使用「無明確定的行為」,便是犯了錯誤。如果它們可以成功執行,那只是運氣使然。「無名確定義的行為」起因於未被編譯器偵測到、或太難被偵測到的程式錯誤。

不幸的是,程式如果代有無明確定義的行為,在某些情況和(或)在某個編譯器下也許能正確執行,卻無法保證在不同編譯器下或甚至目前編譯器的新版本下繼續正確執行。並且即使在某一組輸入下能夠成功執行,也不能保證在其他輸入下能夠成功。

因此,程式不應該(故意地)倚賴「無明確定義的行為」!

同樣道理,程式通常不應該倚賴與機器相依的行為,例如「假設int的大小固定且已知」等等。這種程式被稱為不可移植(nonportable)。當這種程式被移植到其他機器,我們就必須找出並修正任何與機器相依的程式碼。在原本可運行的程式中追蹤這一類的問題,說得溫和點,是件極不愉快的工作。』

這裡好像只提到機器的問題,但是很多情形在不同作業系統下也造成不可移植的問題,之前在做論文時找到了一些在Unix下執行的C程式,但是拿到Windows下完成編譯不起來,最後只好找上Java了,感覺上Java在不同系統上得差異還真是小,不過就是有點感覺到慢。

我喜歡選擇GTK不選擇微軟的圖形使用介面也是考量到移植的問題,但是這是一條很難的路,難怪作者最後說極不愉快的工作。

感謝你看到這裡,很快就可以離開了,但最好的獎勵行動就是按一下幫我分享或留言,感恩喔~

點我分享到Facebook

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *