我可以为整数值编写for..do
过程,但是我无法为int64值编写它。
例如:
var
i:int64;
begin
for i:=1 to 1000 do
end;
编译器拒绝编译这个,为什么会拒绝?
我可以为整数值编写for..do
过程,但是我无法为int64值编写它。
例如:
var
i:int64;
begin
for i:=1 to 1000 do
end;
Delphi编译器目前还不支持Int64循环计数器。
for 循环
中,循环计数器必须是整数(或更小的类型)。这是为了加快 for
循环的执行速度所作的优化。while..do
循环或 repeat..until
循环。即使编译器在Delphi 7的for循环中允许"int64"(Delphi 7???),它可能直到太阳死亡后才能完成完整的迭代。
那你为什么不只是使用“integer”呢?
如果您必须使用int64值...则可以使用“while”循环。
问题解决:)
while
循环,例如:var I: Int64; I := 1; while I <= 30000000000 do begin ...; Inc(I); end;
- Remy Lebeau为什么在for循环中要使用Int64?
很容易回答:
一个例子:
procedure Why_Int64_Would_Be_Great_On_For_Loop;
const
StartValue=5000000000; // Start form 5E9, 5 thousand millons
Quantity=10; // Do it ten times
var
Index:Int64;
begin
for Index:=StartValue to StartValue+Quantity-1
do begin // Bla bla bla
// Do something really fast (only ten times)
end;
end;
那段代码并不需要很长时间,只是索引值需要超过32位整数的限制。
解决方法是使用while循环:
procedure Equivalent_For_Loop_With_Int64_Index;
const
StartValue=5000000000; // Start form 5E9, 5 thousand millons
Quantity=10; // Do it ten times
var
Index:Int64;
begin
Index:=StartValue;
while Index<=StartValue+Quantity
do begin // Bla bla bla
// Do something really fast (only ten times)
Inc(Index);
end;
end;
// I will start the loop from zero, not from two, but i first do some maths to avoid pre-compiler optimizator to convert Index:=Index+Step; to Inc(Index,Step); or better optimization convert it to Inc(Index);
Index:=2;
Step:=Index-1; // Do not put Step:=1; or optimizator will do the convertion to Inc()
Index:=Step-2; // Now fix, the start, so loop will start from zero
while Index<1000000 // 1E6, one millon iterations, from 0 to 999999
do begin
// Do something
Index:=Index+Step; // Optimizator will not change this into Inc(Index), since sees that Step has changed it's value before
end;