Why delphi perform mathematical 'not' of integer rather than force to cast to boolean value in while do looping ? Example
var myint:integer;
...
myint:=1;
while not myint=5 do
begin
myint:=myint+1;
showmessage('myint now is : '+inttostr(myint));
end;
An integer (pronounced IN-tuh-jer) is a whole number (not a fractional number) that can be positive, negative, or zero. Examples of integers are: -5, 1, 5, 8, 97, and 3,043. Examples of numbers that are not integers are: -1.43, 1 3/4, 3.14, . 09, and 5,643.1.
If so you can use the Math. Round method. If the result and the original value are equal then it's an integer.
Types of Integers Integers come in three types: Zero (0) Positive Integers (Natural numbers) Negative Integers (Additive inverse of Natural Numbers)
Hence, a fractional number may not be an integer.
Your expression uses two operators: not
and =
. In order to understand how it is parsed you need to consult the table of operator precedence.
Operators Precedence ---------------------------- @ first (highest) not ---------------------------- * second / div mod and shl shr as ---------------------------- + third - or xor ---------------------------- = fourth (lowest) <> < > <= >= in is ----------------------------
This shows that not
has the highest precedence of all operators, and is of higher precedence than =
. Which means that your expression is parsed as if it were:
(not myint) = 5
In this expression, because it is bound to an integral variable, not
is biwise negation.
In order to get the result that you desire you must use parentheses to indicate that you wish to perform the equality test before the not
:
not (myint = 5)
Now, in this expression, (myint = 5)
is a logical expression and so the not
operator is now logical negation.
The answer to a question of this nature is always found in the table of operator precedence and it will pay dividends to become familiar with this table. This table will tell you how any expression that omits parentheses is parsed.
Finally as Rudy points out, your specific expression is most cleanly written using the <>
operator:
myint <> 5
The reason why delphi is doing this is that the not
operator has a higher order than the equal comparison operator. It is an unary operator which is calculated first. In fact, is has to be calculated first before the =
operator comes into action (which -of course- has the lowest order).
To force delphi calculating what you want, use parenthes:
if not (myint = 5) then....
// vs
if (not myint) = 5 then
// vs
if not myint = 5 then
As you know by now the latter two are equivalent.
BTW: Something similar (order precedence) happens with calculations like 3+4*5
. Here, the multiplication is carried out before the addition because the *
operator has a higher order compared to the +
operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With