Skip to content

Val(): incorrect value for Code (error parameter) for unsigned types if input is negative

Summary

It you use Val() with an unsigned integer type and the inputstring represents a negative number, then Code (the third parameter) does not point to the correct errorposition.

System Information

N/A

Steps to reproduce

var
  U: Word;
  Code: Integer;
begin
  Val('-1',W,Code);
  writeln('Code: ',Code); //outputs: 2
  Val('-0x1',U,Code);
  writeln('Code: ',Code); //outputs: 4
end.

What is the expected (correct) behavior?

In both cases it should output 1.

Possible fixes

The code for the unsigned val-helpers start like this:

  fpc_Val_UInt_Shortstr:=0;
  Code:=InitVal(s,negative,base);
  If Negative or (Code>length(s)) Then  
    Exit;

If negative Code should be set to Pos('-',S)

If so desired I'll create a patch.

To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information