PDA

View Full Version : Making operations on constants into constants



Paulius
25-01-2004, 01:34 PM
I used to think that a:=b/640*pi; should be the same as a:=b/(640*pi); it turns out that in the first case the multiplication happens at runtime and in the second 640*pi is evaluated at compiletime and is a constant at runtime (at least in Delphi6).

Abened
25-01-2004, 02:20 PM
I know it doesn't really answers the post but i always though a = b/(640*pi) was different from a = b/640*pi because the second one is the same as a = b*pi / 640 to me....
And I don't know at all what is compile time and what is runtime.... (but how did you see that ?)

Perhaps i'm just posting for nothing....

Clootie
25-01-2004, 03:16 PM
First: Abened is right these expression are different
Second: even if you compare a:=b/640/pi; (and) b:=b/(640*pi); -- these statements are proceeded differently because 640 is integer and Pi is extended and auto type conversion is not done in this case.

Traveler
25-01-2004, 03:48 PM
a = b/(640*pi) and a:=b/640*pi will give very different results. If no parentheses are used you work from the left to the right.

Pi is already a constant. 640*pi will also be a constant. How Delphi handles this, I do not know for sure. It is likely though that constants are calculated beforehand, ie. at compile time and not at runtime. But if you want to be sure, you can always do it your self: const pi2 = pi * 640;

@Abened: Compile time is when Delphi compiles your program. Runtime is when the program is actually running. Designtime is when you 'design' your program, ie the coding and placing components on the form etc.

[edit: seems a bit like double posting but at the time of writing clootie had not answered :? ]

Paulius
25-01-2004, 04:53 PM
I mistyped there, I meant to write it like Clootie did, but after his remark I took a look at the CPU window with a:=b / (480.0 * 640.0);
and a:=b / 480.0 / 640.0; the first one had no fmul's, and the second one had 2 fdiv's

Clootie
25-01-2004, 05:59 PM
So, Delphi compiler doesn't like to optimize these king of expressions. It's an interesting question why, but solution in this case is to use predefined constants. And it's way better to define it as: PiX = 1 / (Pi * 640);