The compiler can optimize the code, but you cannot expect it to perform magic tricks in your code.
Optimization is highly dependent on your code and the use of your code. For example, if you use foo as follows:
foo(12345);
The compiler can greatly optimize the code. Even he can calculate the result at compile time.
But if you use it like this:
int k; cin >> k; foo(k);
In this case, it cannot get rid of the internal if (the value is provided at run time).
I wrote sample code with MinGW / GCC-4.8.0:
void foo(const int constant) { int x = 0; for (int i = 0; i < 1000000; i++) { x++; if (constant < 10) { x--; } } cout << x << endl; } int main() { int k; cin >> k; foo(k); }
Check out the build code:
004015E1 MOV EAX,0F4240 // i = 1000000 004015E6 MOV EBP,ESP 004015E8 XOR EDX,EDX 004015EA PUSH ESI 004015EB PUSH EBX 004015EC SUB ESP,10 004015EF MOV EBX,DWORD PTR SS:[EBP+8] 004015F2 XOR ECX,ECX // set ECX to 0 004015F4 CMP EBX,0A // if constant < 10 ^^^^^^^^^^ 004015F7 SETGE CL // then set ECX to 1 004015FA ADD EDX,ECX // add ECX to i 004015FC SUB EAX,1 // i
As you can see, the internal if code exists in the code. See CMP EBX,0A .
I repeat, it is highly dependent on lines with loops.
deepmax
source share