Thursday, June 19, 2008

Don’t Rely on Undefined Behavior

C++ Primer 4/e has again a good advice:『
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.』
Chinese translation said:『程式如果使用「無明確定的行為」,便是犯了錯誤。如果它們可以成功執行,那只是運氣使然。「無名確定義的行為」起因於未被編譯器偵測到、或太難被偵測到的程式錯誤。
不幸的是,程式如果代有無明確定義的行為,在某些情況和(或)在某個編譯器下也許能正確執行,卻無法保證在不同編譯器下或甚至目前編譯器的新版本下繼續正確執行。並且即使在某一組輸入下能夠成功執行,也不能保證在其他輸入下能夠成功。
因此,程式不應該(故意地)倚賴「無明確定義的行為」!
同樣道理,程式通常不應該倚賴與機器相依的行為,例如「假設int的大小固定且已知」等等。這種程式被稱為不可移植(nonportable)。當這種程式被移植到其他機器,我們就必須找出並修正任何與機器相依的程式碼。在原本可運行的程式中追蹤這一類的問題,說得溫和點,是件極不愉快的工作。』
Here may be mentioned the machine's problems, but many situations in different OS it makes the nonportable problems.Last year I wrote the paper and found many source codes running at Unix.But it can't be compiled at Windows.So finally I use Java to code.Although I feel Java is some slow,it can run at many different OS.
I like to choice GTK and not choice Microsoft GUI .Because I concern the portable problem.But it is diffcult to use GTK.So I like the author said : "a profoundly unleasent task".

No comments: