I'm not sure it's as easy as "give me an example of where I'm wrong". First of all, the rules cpjust gives are useful - if your application runs in half a second, most people won't care if you get it down to a quarter second. Obviously, if it takes half a minute or more, there may be room for improvement. In this, find the part of code that runs for the longest time and try to find a way to make that run faster.
But the important rule here is also that "it's hard to beat the compiler".
And just to prove the point:
Code:
int func1(int *x)
{
int *ptr = &x[4];
int ans = *ptr + *(ptr+1);
return ans;
}
int func2(int *x)
{
int ans = x[4] + x[5];
return ans;
}
// Sample Program A
int main()
{
int x[10] = {0};
int i;
for(i = 0; i < 10; i++) {
x[i] = i;
}
printf("func1: %d, func2: %d\n", func1(x), func2(x));
return 0;
}
becomes [snipped for brevity]:
Code:
_func1:
movl 4(%esp), %edx
movl 20(%edx), %eax
movl 16(%edx), %ecx
addl %ecx, %eax
ret
.globl _func2
_func2:
movl 4(%esp), %edx
movl 20(%edx), %eax
movl 16(%edx), %ecx
addl %ecx, %eax
ret
This is from gcc 3.4.2, with -fomit-frame-pointer -O3.
So the difference between your two examples is absolutely NOTHING. Just a bit more C-code and harder to understand in example one, which isn't a benefit.
As I have said before, there are different processor architectures, and some C constructions may be more or less efficient in some ways, but as long as the result is correct, the compiler can pretty much do as it likes with how it generates the actual code.
It is entirely possible to make the compiler generate WORSE code by "confusing the compiler", e.g. using more variables and making things more complex.
--
Mats