use of **and** operator within an **if statement**
Asked Answered
A

4

6

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

Astrophotography answered 30/3, 2011 at 15:38 Comment(1)
A hint for future questions: When you say "I get an error", you need to say what the error is, so we'll know what to look for more easily. Remember, we can't see your screen from here. :)Pore
P
34

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.

Pyuria answered 30/3, 2011 at 15:40 Comment(4)
"and I need to write more characters to be submitted" <- haha :DDorren
Also abc and def must be declared, if it's string values(not variables) have to be wrapped with quotes 'abc' and 'def'Frostbitten
@Daniel, I removed the sentence you cited, and completed my answer, to be (trying) more explanatoryPyuria
Isn't it a=(abc and b)=def, rather than a=(abc and b=def)?Silvestro
P
11

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.

Proponent answered 30/3, 2011 at 15:47 Comment(0)
B
8

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

Bandstand answered 31/3, 2011 at 23:50 Comment(0)
E
2

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

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

Eyesore answered 31/3, 2011 at 5:28 Comment(1)
It's just an example, the problem is not about the apostrophes. abc and def are just variables.Proponent

© 2022 - 2024 — McMap. All rights reserved.