C 的历史问题:undefined behavior
简写为 UB
“Anything at all can happens; the Standard imposes no requirements. The program may fail to compile, or it may execute incorrectly (either crashing or silently generating incorrect results), or it may fortuitously do exactly what the programmer intended”
简单来说就是:他没定义这种操作该怎么办。
比如说 / 0 以及一些你们可能没接触过的操作。
给你们看个恶心的例子:
int main(int argc, char **argv) {
int i = 3;
int r = (i++*++i+i--*--i);
printf("The answer : %dn", r);
system("pause");
return 0;
}
讓我們看看不同編譯器的 Debug 模式下執行的結果
Visual C++ 6.0
The answer : 25
Visual C++ 2008 Express
The answer : 18
MinGW(GCC)
The answer : 25
我們試試看在 Release 下執行的結果
Visual C++ 6.0
The answer : 18
Visual C++ 2008 Express
The answer : 18
MinGW(GCC)
The answer : 25
C 語言最初為了開發 UNIX 和系統軟體而生,本質是低階的程式語言,
在語言規範層級存在 UB,可允許編譯器引入更多最佳化。比方說 X * 2 / 2
在沒有 overflow 發生的時候,可最佳化為 X
。
而且值得注意的是,在你的程序初始化之前,栈里面塞的一堆东西也是 UB。
但是高级语言比如说 java,python 都不会出现这样的问题了。
因为发现少一个时钟周期的运算多一堆问题,完全得不偿失啊。
当然,有更多兴趣的话可以看看这个东西
关键是,老师喜欢出题刁难你啊!真烦啊!