Jayesh Jayesh - 1 year ago 45
C Question

Which code will execute faster in C?

I saw the following code(Ques. 3) on PUZZLERSWORLD.COM site.

Code 1 :

for(i=0; i<1000; i++)
for(j=0; j<100; j++)
x = y;

Code 2 :

for(i=0; i<100; i++)
for(j=0; j<1000; j++)
x = y;

Which code will execute faster?


a) Code 1 and Code 2 are of same speed,
b) Code 1,
c) Code 2,
d) Can't Say



So, I have a question, Why second code faster then first?

Answer Source

Unless y is declared as volatile, both codes can be reduced into:

x = y;


int f(int y)
    int x;

    for (int i = 0; i < 1000; i++)
        for (int j = 0; j < 100; j++)
            x = y;
    return x;


        mov     eax, edi
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download