变量自身初始化
Variable initialization with itself
写这样的代码安全吗?
#include <iostream>
int main()
{
int x = x-x;// always 0
int y = (y)? y/y : --y/y // always 1
}
我知道有未定义的行为,但在这种情况下它不只是一个垃圾值吗?如果是,则相同值减相同值始终为 0,相同值除以自身(不包括 0)始终为 1。如果不想使用整型文字,这很重要,不是吗? (佯攻)
未定义行为未定义。总是。在某些平台上,东西可能或多或少可靠地工作或损坏,但总的来说,你不能依赖这个程序不会崩溃或任何具有特定值的变量。
未定义的行为就是未定义的行为。没有 "isn't it in this case something specific" (除非您实际上是在谈论完整编译的结果,并查看生成的机器代码,但那不再是 C++)。编译器可以为所欲为。
I know there is undefined behaviour, but isn't it in this case just a trash value? If it is, then same value minus same is always 0, and same value divided by itself (excluding 0) is always 1.
不!不不不!
"trash value" 是一个 "indeterminate value"。
从自身中减去不确定的值不会产生零:它会导致您的程序具有未定义的行为([C++14: 8.5/12]
)。
您不能依赖正常的算术规则来 "cancel out" 未定义的行为。
Your program could travel back in time 并破坏 权力的游戏/原力觉醒/女超人 为了每一个。请不要这样做!
请允许我演示未定义行为的邪恶魔法:
给定:
#include <iostream>
int main()
{
using namespace std;
int x = x-x;// always 0
int y = (y)? y/y : --y/y; // always 1
cout << x << ", " << y << endl;
return 0;
}
apple clang,用-O3
编译:
输出:
1439098744, 0
未定义为 未定义。上面代码中的注释是谎言,这将使您的随机数生成器的未来维护者感到困惑;-)
写这样的代码安全吗?
#include <iostream>
int main()
{
int x = x-x;// always 0
int y = (y)? y/y : --y/y // always 1
}
我知道有未定义的行为,但在这种情况下它不只是一个垃圾值吗?如果是,则相同值减相同值始终为 0,相同值除以自身(不包括 0)始终为 1。如果不想使用整型文字,这很重要,不是吗? (佯攻)
未定义行为未定义。总是。在某些平台上,东西可能或多或少可靠地工作或损坏,但总的来说,你不能依赖这个程序不会崩溃或任何具有特定值的变量。
未定义的行为就是未定义的行为。没有 "isn't it in this case something specific" (除非您实际上是在谈论完整编译的结果,并查看生成的机器代码,但那不再是 C++)。编译器可以为所欲为。
I know there is undefined behaviour, but isn't it in this case just a trash value? If it is, then same value minus same is always 0, and same value divided by itself (excluding 0) is always 1.
不!不不不!
"trash value" 是一个 "indeterminate value"。
从自身中减去不确定的值不会产生零:它会导致您的程序具有未定义的行为([C++14: 8.5/12]
)。
您不能依赖正常的算术规则来 "cancel out" 未定义的行为。
Your program could travel back in time 并破坏 权力的游戏/原力觉醒/女超人 为了每一个。请不要这样做!
请允许我演示未定义行为的邪恶魔法:
给定:
#include <iostream>
int main()
{
using namespace std;
int x = x-x;// always 0
int y = (y)? y/y : --y/y; // always 1
cout << x << ", " << y << endl;
return 0;
}
apple clang,用-O3
编译:
输出:
1439098744, 0
未定义为 未定义。上面代码中的注释是谎言,这将使您的随机数生成器的未来维护者感到困惑;-)