Could (x == 0) be more efficient than (0 == x)?

Possible duplicate:
Which one will run faster if (flag == 0) or if (0 == flag)?

Usually I write my terms of equality:

if(0==x)

as many people do, instead

if(x==0) 

for the compiler to tell me when I accidentally typed = instead of ==.

Someone told me that some compilers implement this as two register loads, rather than a single operation with zero, and therefore it is less efficient.

Does anyone know if this is a reasonable comment?

+3
source share
5 answers

Someone told me that some compilers implement this as two register loads, rather than using a zero operation

. , , , : , , .

, true operator ==. operator ==, .

+8

, " ", , , , , .

+4

. , . , , 0 .

, :

if(conditionA && conditionB && (conditionC || conditionD)) {...}

A , if, , , .

0

, , , , . ?

#include <stdio.h>
#include <stdlib.h>

    int main(int argc, char *argv[]) {
        int x = atoi(argv[1]);
        int zeros=0;
        int i;
        for (i=0; i<100000; i++) {
            if (0==x) {
                zeros++;
            }
        }
        printf("zeros: %d\n",zeros);
        return 0;
    }
0

Why not try 2 solutions?

#include <stdio.h>
#include <time.h>

#define LOOPS   1000000000

void main(void)
{
    clock_t start1, start2, end1, end2;
    int x=1,i;

    start1=clock();
    for(i=0;i<LOOPS;i++)
    {
        if (x==0)
        {
            x=1;
        }
    }
    end1=clock();

    start2=clock();
    for(i=0;i<LOOPS;i++)
    {
        if (0==x)
        {
            x=1;
        }
    }
    end2=clock();

    printf("x==0 %d ns\n", end1-start1);
    printf("0==x %d ns\n", end2-start2);
}
0
source

All Articles