use of **and** operator within an **if statement**
-
14-11-2019 - |
سؤال
I was directed to this website by a friend.
I am trying to use and
in Delphi, but I seem to be doing something wrong. Is there something you need to put in uses?
I have the following code:
procedure TForm1.Button1Click(Sender: TObject);
var
a,b:string;
begin
a:=edit1.Text;
b:=edit2.Text;
if a=abc and b=def then
showmessage(a+b);
end;
I get an error at the second = sign
المحلول
You have to put some parentheses to change the operator precedence:
if (a=abc) and (b=def) then
Operator and
precedes =
so the construction without parenthesis is understood as
a=(abc and b=def)
which produces the syntax error.
نصائح أخرى
and
has a higher precedence than =
. So if a=abc and b=def then
becomes if a=(abc and b)=def then
, which is not valid. So write it like if (a=abc) and (b=def) then
.
The Operator Precedence rules for Delphi are tripping you up. There are four levels.
- @, NOT
- *, /, div, mod, and, shl, shr, as
- +, -, or, xor
- =, <>, <, >, <=, >=, in, is
In your example the AND comparison will take place first unless you use brackets to force the equality comparisons to be done first.
Surely there are apostrophes missing from the strings - the statement should be
if (a = 'abc') and (b = 'def') then ...