are there a compiler switches to evaluate constant expression at compile time ?The compiler automatically does constant propagation depending on the general optimization switches. However dynamic arrays (for example) are not part of these optimizations.
var a : array of longint; i : longint; begin setlength(a,9); for i:= 0 to length(a)-1 do a[i] := i; end.
HiLet's change that a bit:
are there a compiler switches to evaluate constant expression at compile time ?
for example
var a : array of longint; i : longint; begin setlength(a,9); for i:= 0 to length(a)-1 do a[i] := i; end.
# [5] for i:= 0 to length(a)-1 do
movl $-1,U_$P$PROGRAM_$$_I
.p2align 4,,10
.p2align 3
.Lj3:
movl U_$P$PROGRAM_$$_I,%eax
leal 1(%eax),%eax
movl %eax,U_$P$PROGRAM_$$_I
# [6] a[i] := i;
movl U_$P$PROGRAM_$$_I,%eax
movl U_$P$PROGRAM_$$_I,%edx
movl %edx,U_$P$PROGRAM_$$_A(,%rax,4)
cmpl $8,U_$P$PROGRAM_$$_I
jge .Lj5
jmp .Lj3
Same as you wish? Optimization level 0, btw :) (O3 will activate loop unrolling, totally removing the loop).Wirthian optimization :):)
const L = 9; var a: array of LongInt; i: LongInt; begin SetLength(a, L); for i := 0 to L - 1 do a[i] := i; end.
Length() is a compiler intrinsic, its implementation depends on type of given data. In static arrays, its replaced directly by a constant. In dynamic arrays, it's located at negative offset of the array (4 bytes to the left to be precise), much like all dynamic strings, hence requires a little computation that can't be replaced by a constant. Check this short programmer's guide (https://www.freepascal.org/docs-html/prog/progsu164.html) page.Well, for local dynamic arrays the compiler could in theory keep the length of the array in a register as well (as long as the array isn't passed to some other function) and thus generate more optimized code.