Hi,
I just came across the following problem: In a program for numerical computations I use constants for variables with a fixed value because I hope the compiler can produce faster code then. This gives me compiletime errors (division by zero) in code like that:
***********************************
CONST a=0; VAR b: double;
BEGIN IF a<>0 THEN b:=10/a; END.
***********************************
I tried to look this up in the extended pascal standard and found nothing that would make the above code fragment illegal. But the standard is not quite easy to read, so it is very possible I just didn´t understand it. Is this behaviour dependent on compiler switches?
On Tue, 31 Oct 2000, Sven Sahle wrote:
CONST a=0; VAR b: double;
BEGIN IF a<>0 THEN b:=10/a; END.
Writing the type of your constant helps here. For example:
CONST a:double = 0
Regards, Adam Naumowicz
-------------------------------------- WWW: http://math.uwb.edu.pl/~adamn/ --------------------------------------
Sven Sahle a écrit :
Hi,
I just came across the following problem: In a program for numerical computations I use constants for variables with a fixed value because I hope the compiler can produce faster code then. This gives me compiletime errors (division by zero) in code like that:
CONST a=0; VAR b: double;
BEGIN IF a<>0 THEN b:=10/a; END.
I tried to look this up in the extended pascal standard and found nothing that would make the above code fragment illegal. But the standard is not quite easy to read, so it is very possible I just didn´t understand it. Is this behaviour dependent on compiler switches?
This is a side effect of gpc compiler optimisation. The bug is detected at _compile_ time, not at _execution_ time. At compile time a is known to be always zero because it is const, and there is no way (at least no easy way) to detect at compile time that the if clause will prevent the program to ever go there at execution time. Replacing by
CONST a:double = 0
as suggested by Adam cures the problem because a "typed constant" is in fact an initialized variable which value could be changed during program execution, so that nothing can securely be inferred at compile time about its value at execution time.
So this is in fact a wise behavior of gpc.
Maurice