Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

  1. @, NOT
  2. *, /, div, mod, and, shl, shr, as
  3. +, -, or, xor
  4. =, <>, <, >, <=, >=, 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.

Expressions (Delphi) - Operator Precedence

Surely there are apostrophes missing from the strings - the statement should be

if (a = 'abc') and (b = 'def') then ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top