在数组(字符串)的边界之外读取是否可以接受?

Is it acceptable to read outside the bound of an array (string)?

我研究了一点 Delphi 源代码,这对我来说有点难看(在 system.pas,程序 ValLong 中):

while True do
begin
  case S[I] of
    '0'..'9': Dig := Ord(S[I]) - Ord('0');
  else
    Break;
  end;
  if (Result < 0) or (Result > (High(Integer) div 10)) then
    Break;
  Result := Result*10 + Dig;
  Inc(I);
  Empty := False;
end;

如您所见,跳出循环的唯一方法是读取 S(字符串)的边界之外。我是否遗漏了什么,这是正确的做法吗?

Unicode 字符串、AnsiString 和 WideString 类型始终以空字符结尾。

来自Internal Data Formats-Long String Types

The NULL character at the end of a string memory block is automatically maintained by the compiler and the built-in string handling routines. This makes it possible to typecast a string directly to a null-terminated string.

因此,可以放心地相信这些类型是空终止的。问题中的代码示例没问题

注意:我假设范围检查已关闭,因为此代码来自 RTL。否则索引空字符时会出现异常