I want to find where the leading zero ends in a string? but a unexpected problems happened...
for(i=2980;(bin[i]==0)&&(i>=0);i--);//this failed to past
for(i=2980;i>=0&&bin[i]==0;i--);//this is accepted by testing-web
but I think this two expressions have the same meaning..I can't find the reason ,please help me, thank you.
CodePudding user response:
I think this two expressions have the same meaning
They do not. They differ.
a && b
is a "short-circuit" evaluation.
If a
is false, b
is not evaluated.
If a
is true, then b
is evaluated.
Consider what happens when i == -1
:
// Only (-1 >= 0) evaluated
// Since it was false bin[-1]==0 was not attempted.
(i >= 0) && (bin[i]==0)
// Code first tries bin[-1], which is outside the array bin[]
// Result: undefined behavior (UB).
// In OP's case, program failed.
(bin[i]==0) && (i>=0)
CodePudding user response:
Let's look at how the for loop works...
Let's say i is 0:
for (i=2980; (bin[i]==0)&&(i>=0);i--)
Replacing i with 0 gives:
for (i=2980; (bin[0]==0)&&(0>=0);i--)
This is OK because 0 is a valid index. It then runs i-- and now i == -1 and it runs the for
loop again:
for (i=2980; (bin[-1]==0)&&(-1>=0);i--)
So -1 is an invalid index. Swapping those two operations around "short circuits" the check and because (-1>=0)
fails, it never runs bin[-1]==0
.