Nep*_*low -1 c variables if-statement machine-code low-level-code
While typing a program as a high level programmer, n = 0;
looks more efficient and clean.
But is n = 0;
really more efficient than if (n != 0) n = 0;
?
when n
is more likely to be 0
.
when n
is less likely to be 0
.
when n
is absolutely uncertainty.
Language: C (C90)
Compiler: Borland's Turbo C++
Minimal reproducible code
void scanf();
void main()
{
int n; // 2 bytes
n=0; // Expression 1
scanf("%d",&n); // Absolutely uncertain
if(n!=0) n=0; // Expression 2
}
Run Code Online (Sandbox Code Playgroud)
Note: I have mentioned the above code only for your reference. Please don't go with it's flow.
If your not comfortable with the above language/standard/compiler, then please feel free to explain the above 3 cases in your preferred language/standard/compiler.
如果n
是2的补码整数类型或无符号整数类型,那么n = 0
直接写入肯定不会比带有条件检查的版本慢,并且良好的优化编译器将生成相同的代码。一些编译器将寄存器值与自身进行XOR运算,从而将赋值编译为零,这是一条指令。
如果n
是浮点类型,1's补码整数类型或有符号幅度整数类型,则两个代码段的行为会有所不同。例如,如果n
签名为负零。(确认@chqrlie。)如果n
系统上的指针具有多个空指针表示形式,则当各种空指针之一时,if (n != 0) n = 0;
也不会分配。 赋予不同的功能。n
n
n = 0;
“将永远更有效率”是不正确的。应阅读n
具有成本低,写n
成本高(想想,再写入非易失性存储器的需要重新编写一个页面),并有可能n == 0
,则n = 0;
比较慢,少效率比if (n != 0) n = 0;
。