Entry No.
494
|
Compiler - Code generation
Using Low(integer) and High(integer) in for loops
produces bad code.
|
|
| 1.02 |
2.01 |
3.0 |
3.01 |
3.02 |
4.0 |
4.01 |
4.02 |
4.03 |
5.0 |
5.01 |
6.0 |
6.01 |
6.02 |
Kylix 1.0 |
| Absent | Exists | Exists | Exists | Exists | Exists | Exists | Exists | Exists | Exists | Exists | Exists | Exists | Exists | Exists |
|
|
|
Description | |
Reported by Anders Melander; checked by Reinier Sterkenburg
For example:
for i := low(integer) to high(integer) do
Label1.Caption := IntToStr(i);
When compiling this, D4.x gives a hint that says that the for
loop executes 0 times and that it has been deleted...
Further testing shows that
for i := low(integer) downto high(integer) do ;
is not removed by the optimizer.
Even though low(integer) is negative and high(integer) is positive when
you display them with IntToStr(), it appears that the for loop treats the
values as unsigned DWORDs (verified with CPU window). |
|
|
User-contributed comments | |
bin 30 Jan 2003 01:51 PM GMT |
If you try such a construction in C you will get an infinite loop. The reason is in the point where the loop control variable is checked for the exit condition. I don't know exactly how the construction from the example is compiled in delphi but a for loop like this:
var i: byte;
....
for i:=0 to 255 do;
will not cause an endless loop like in C. This is because of the way the construction is compiled, it is optimized for the above case. Still the case of a loop from the lowest to the highest value of a variable can have side effects caused by wrapping.
|
|