Recent

Author Topic: Docs: CompareChar, invalid result  (Read 524 times)

Fibonacci

  • Hero Member
  • *****
  • Posts: 577
  • Internal Error Hunter
Docs: CompareChar, invalid result
« on: October 21, 2024, 03:35:58 pm »
https://www.freepascal.org/docs-html/rtl/system/comparechar.html
Quote
The function returns one of the following values:

-1
    if buf1 and buf2 contain different characters in the first len positions, and the first such character is smaller in buf1 than the character at the same position in buf2.
0
    if the first len characters in buf1 and buf2 are equal.
1
    if buf1 and buf2 contain different characters in the first len positions, and the first such character is larger in buf1 than the character at the same position in buf2.

This means the possible result values are -1, 0, and 1; while in practice, it behaves like CompareByte and returns the difference between the character values in the ASCII table.

Code: Pascal  [Select][+][-]
  1. var
  2.   s, d: string;
  3. begin
  4.   s := 'testaxxx';
  5.   d := 'testxxxx';
  6.   writeln(CompareChar(s[1], d[1], length(s)));
  7. end.

It prints -23, the difference between Ord('a') and Ord('x').

Actually implementation of CompareChar is to use CompareByte:

Code: Pascal  [Select][+][-]
  1. function CompareChar(Const buf1,buf2;len:SizeInt):SizeInt;
  2. begin
  3.   CompareChar:=CompareByte(buf1,buf2,len);
  4. end;

Bart

  • Hero Member
  • *****
  • Posts: 5447
    • Bart en Mariska's Webstek
Re: Docs: CompareChar, invalid result
« Reply #1 on: October 21, 2024, 06:29:55 pm »
File a bugreport in fpc's documentation bugtracker.

Bart

Fibonacci

  • Hero Member
  • *****
  • Posts: 577
  • Internal Error Hunter
Re: Docs: CompareChar, invalid result
« Reply #2 on: October 21, 2024, 06:40:37 pm »
Thanks, wasnt aware there is a doc bugtracker :)

https://gitlab.com/freepascal.org/fpc/documentation/-/issues/39402

ASerge

  • Hero Member
  • *****
  • Posts: 2336
Re: Docs: CompareChar, invalid result
« Reply #3 on: October 21, 2024, 07:56:53 pm »
The same bug in documentation of the CompareWord, CompareDWord, but not in CompareChar0, CompareByte.

Thaddy

  • Hero Member
  • *****
  • Posts: 15992
  • Censorship about opinions does not belong here.
Re: Docs: CompareChar, invalid result
« Reply #4 on: October 22, 2024, 10:16:04 am »
Note that the distance is very valuable. In many cases you need that distance, not just -1,0,1.
If I smell bad code it usually is bad code and that includes my own code.

Zoran

  • Hero Member
  • *****
  • Posts: 1870
    • http://wiki.lazarus.freepascal.org/User:Zoran
Re: Docs: CompareChar, invalid result
« Reply #5 on: October 22, 2024, 06:56:27 pm »
Note that the distance is very valuable. In many cases you need that distance, not just -1,0,1.

You shouldn't rely on return value being the distance. This is not documented.

 

TinyPortal © 2005-2018