Vini
Vini

Reputation: 2134

Difference between evaluation of while(n>0) and while(n!=0)

Is the evaluation of while(n>0) and while(n!=0) different? Basically both are to exit in the same condition. So is there a scenario when one of them should be used? Or will it make a difference in the performance efficiency by changing the loop condition when the number of times the loop being evaluated being the same?

Upvotes: 4

Views: 687

Answers (3)

user1196549
user1196549

Reputation:

In general, the difference will be neutral.

Anyway, one could maliciously think of special schemes like

while (n > 0)
{
  ...
  n++;
}

vs.

while (n != 0)
{
  ...
  n++;
}

where the compiler can infer that in the first snippet the test needs to be done on the first iteration only, and unroll the while into an if.

Upvotes: 1

fedorshishi
fedorshishi

Reputation: 1477

This depends on your platform, but in general, it will perform identically. For example, for x86 architecture cmp operator will be used for both > or !=. Here you can read more.

Upvotes: 3

Henry
Henry

Reputation: 43728

Apart from the fact that the condition is not the same, there is no difference performance wise.

Upvotes: 1

Related Questions