看完后隐藏功能和C++/STL的暗角上comp.lang.c++.moderated,我完全惊讶的是,下面的代码片断编译并在两个Visual Studio 2008和G ++ 4.4的工作.
这是代码:
#include <stdio.h>
int main()
{
int x = 10;
while (x --> 0) // x goes to 0
{
printf("%d ", x);
}
}
Run Code Online (Sandbox Code Playgroud)
我假设这是C,因为它也适用于GCC.标准中定义了哪里,它来自何处?
考虑
#include <iostream>
int main()
{
double a = 1.0 / 0;
double b = -1.0 / 0;
double c = 0.0 / 0;
std::cout << a << b << c; // to stop compilers from optimising out the code.
}
Run Code Online (Sandbox Code Playgroud)
我一直认为这a将是+ Inf,b将是-Inf,并且c将是NaN.但我也听到传言说严格来说浮点除零的行为是未定义的,因此上面的代码不能被认为是可移植的C++.(理论上,这会消除我的百万行加上代码堆栈的完整性.糟糕.)
谁是对的?
注意我对实现定义感到满意,但我在谈论吃猫,在这里恶魔打喷嚏的未定义行为.
c++ floating-point divide-by-zero undefined-behavior language-lawyer
以下代码片段会导致代码过早退出。我的问题是为什么我的系统仍然显示Program finished with exit code 0.
#include <stdio.h>
int main(void) {
int divisor = 0;
int dividend = 0;
int quotient = 0;
printf("BEGIN\n");
quotient = dividend / divisor;
printf("END\n"); // This statement does not execute
return 0;
}
Run Code Online (Sandbox Code Playgroud) 如果x为0,则打印0.如果y为0,则会出错.
为什么是这样?我唯一能想到的是布尔表达式编译的顺序很重要.如果x为0,则得到(false)&&(错误值),其中false在左侧,如果y为0,则得到(错误值)&&(false).为什么会影响打印的内容?
int main(void) {
int x = 1;
int y = 0;
int a = (x/y > 0)&&(y/x > 0);
printf("%d\n", a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)