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不选择微软的图形使用介面也是考量到移植的问题,但是这是一条很难的路,难怪作者最后说极不愉快的工作。