逻辑、关系与按位运算符

1 逻辑运算符包含:andornotxor

这类运算符接收布尔值作为参数,运算结果也为布尔值;

当两侧操作数都是整数时,and/or/not/xor 会变为按位运算符,运算结果是整数。

2 关系(比较)运算符:=<>><<=>=

如果你熟悉 C 系列语言,需要重点区分:

Pascal 判断相等只用单个等号 A = B(C 语言是 A == B);

Pascal 的赋值运算符是专用符号 :=

逻辑 / 按位运算符的运算优先级高于关系运算符

想要控制计算顺序,部分表达式必须用括号包裹,否则逻辑会出错甚至编译失败。

错误示例(编译报错)

var
  A, B: Integer;
begin
  if A = 0 and B <> 0 then ... // 错误写法Code language: JavaScript (javascript)

编译失败原因:

编译器优先级规则会先执行中间的按位与 0 and B(得到整数);

再执行 A = (0 and B),得到布尔值;

最后程序试图把布尔值和整数 0 继续运算,触发类型不匹配(type mismatch)

正确写法

var
  A, B: Integer;
begin
  if (A = 0) and (B <> 0) then ...Code language: HTML, XML (xml)

短路求值规则(Short-circuit evaluation)

以表达式 if MyFunction(X) and MyOtherFunction(Y) then... 举例,规则如下:

  1. and 运算:先执行左侧 MyFunction(X)
    • 若左侧返回 false,整个表达式结果必然是 false,右侧函数 MyOtherFunction(Y) 完全不会执行
  2. or 运算同理:
    • 若左侧已经返回 true,整体结果一定为真,右侧代码不再执行。

该特性在空指针判断时非常实用:

if (A <> nil) and A.IsValid then...Code language: HTML, XML (xml)

即便 A 是空指针 nil,代码也不会崩溃。 关键字 nil 代表空指针,数值层面等价于 0,对应其他语言里的 null。

运算符分类

关系运算符(返回 Boolean)

Pascal含义C 等价
=等于==
<>不等于!=
>大于>
<小于<
>=大于等于>=
<=小于等于<=

逻辑 / 按位运算符

not:逻辑非 / 按位取反 and:逻辑与 / 按位与 or:逻辑或 / 按位或 xor:逻辑异或 / 按位异或

not 非

anot a
truefalse
falsetrue

and 与(全真才真)

aba and b
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse

or 或(一真即真)

aba or b
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse

xor 异或(两边不同才为真)

aba xor b
truetruefalse
truefalsetrue
falsetruetrue
falsefalsefalse

例子

闰年判断规则

  1. 能被 4 整除,但不能被 100 整除 → 闰年
  2. 能被 400 整除 → 闰年 其余为平年
{$ifdef FPC} {$mode objfpc} {$H+} {$endif}
{$codepage utf8}
program LeapYearCheck;

// 判断闰年函数,输入年份,返回布尔值
function IsLeapYear(year: Integer): Boolean;
begin
  Result := ((year mod 4 = 0) and (year mod 100 <> 0)) or (year mod 400 = 0);
end;

var
  y: Integer;
begin
  Write('请输入年份:');
  ReadLn(y);

  if IsLeapYear(y) then
    Writeln(y, ' 是闰年')
  else
    Writeln(y, ' 是平年');

  ReadLn;
end.Code language: JavaScript (javascript)
  • mod 取余运算符,year mod 4 = 0 代表能被 4 整除
  • 表达式必须加括号:and 优先级高于比较运算符
  • 短路特性:or 前面满足 400 整除时,不会再判断前面的 4/100 条件

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注