if (n!=0) n=0; v/s n=0; Which is more efficient and why?

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;?

  1. when n is more likely to be 0.

  2. when n is less likely to be 0.

  3. 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.

Bat*_*eba 5

如果n是2的补码整数类型或无符号整数类型,那么n = 0直接写入肯定不会比带有条件检查的版本慢,并且良好的优化编译器将生成相同的代码。一些编译器将寄存器值与自身进行XOR运算,从而将赋值编译为零,这是一条指令。

如果n是浮点类型,1's补码整数类型或有符号幅度整数类型,则两个代码段的行为会有所不同。例如,如果n签名为负零。(确认@chqrlie。)如果n系统上的指针具有多个空指针表示形式,则当各种空指针之一时,if (n != 0) n = 0;也不会分配。 赋予不同的功能。nnn = 0;

“将永远更有效率”是不正确的。应阅读n具有成本低,写n成本高(想想,再写入非易失性存储器的需要重新编写一个页面),并有可能n == 0,则n = 0;比较慢,效率比if (n != 0) n = 0;

  • @chqrlie:已经晚了!好点,我偷了它。 (2认同)
  • 为了完整起见,我们可以添加负零的行为不限于浮点类型,在不可能的体系结构中,整数使用1的补码或正负号/幅值表示。...要考虑的另一种特殊情况是是否定义了n作为`volatile'。对其进行写入可能会产生有害的副作用。 (2认同)
  • @ chux-ReinstateMonica:是时候对此进行Wiki-请在闲暇时添加文稿。 (2认同)