Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiency of boolean comparisons? In C

I'm writing a loop in C, and I am just wondering on how to optimize it a bit. It's not crucial here as I'm just practicing, but for further knowledge, I'd like to know:

In a loop, for example the following snippet:

int i = 0;
while (i < 10) {
    printf("%d\n", i);
    i++;
}

Does the processor check both (i < 10) and (i == 10) for every iteration? Or does it just check (i < 10) and, if it's true, continue?

If it checks both, wouldn't:

int i = 0;
while (i != 10) {
    printf("%d\n", i);
    i++;
}

be more efficient?

Thanks!

like image 255
Wolfin Avatar asked Dec 03 '22 04:12

Wolfin


1 Answers

Both will be translated in a single assembly instruction. Most CPUs have comparison instructions for LESS THAN, for LESS THAN OR EQUAL, for EQUAL and for NOT EQUAL.

like image 66
mouviciel Avatar answered Dec 23 '22 19:12

mouviciel