The question is missing important information for any documented answer.
If for example we have these programs:
int main(void) {
int i, j, x, y;
for (i = 0; i < 1000; i++)
for (j = 0; j < 100; j++)
x = y;
}
and
int main(void) {
int i, j, x, y;
for (i = 0; i < 100; i++)
for (j = 0; j < 1000; j++)
x = y;
}
Both have undefined behavior because they read the value of uninitialized variable y
.
If we have this:
int main(void) {
int i;
unsigned char j;
int x, y = 0;
for (i = 0; i < 1000; i++)
for (j = 0; j < 100; j++)
x = y;
}
and
int main(void) {
int i;
unsigned char j;
int x, y = 0;
for (i = 0; i < 1000; i++)
for (j = 0; j < 100; j++)
x = y;
}
The second code runs forever and the first finishes instantly.
With decent compilers and correct definitions, the code is almost completely optimized out, so answer a) applies:
int main(void) {
int i, j, x, y = 0;
for (i = 0; i < 100; i++)
for (j = 0; j < 1000; j++)
x = y;
}
compiled with Godbolt's compiler explorer, produces:
main:
xorl %eax, %eax
ret
The site expects you to chose c) because the initial overhead of the nested loop is repeated 10 times more in the second code fragment than in the first. While there is some logic in this analysis, it might not be the dominant factor and as explained above other considerations must be studied too, and in any case 900 extra instructions would be negligible compared to several hundreds of thousands for the rest of the code, making it hardly measurable.
In performance analysis, humility is a cardinal virtue. Use profiling tools and carefully write thorough benchmarking code to determine if optimization is useful at all. It is a common mistake to write complex code in a attempt at optimizing and get code that produces incorrect results.
Note that the linked page is full of broken questions. For example Q2:
#include
fun(int i)
{
int j=0;
while (i & i-1) {
j++;
}
printf("%d",j);
}
main(){
f(100);
}
Options: a. 100 b. 99 c. 2 d. 3
The code does not compile, and were it corrected, it has an infinite loop so none of the answers are correct. For the curious, the correct function to compute the number of bits in i
is:
void fun(unsigned i) {
int j = 0;
while (i) {
i = i & (i - 1);
j++;
}
printf("%d\n", j);
}
Out of 10 questions, 7 have incorrect answers and the remaining 3 (Q1, Q4 and Q5) are trick questions with syntax errors. A very poor quality Q&A site indeed.