Warning on comparing a SmallInt with result of Ord function

后端 未结 2 663
清歌不尽
清歌不尽 2021-01-15 10:49

I\'m comparing a SmallInt variable with the result of the Ord function. Example:

var
  MySmallInt : SmallInt;
begin
  MySmallInt :=         


        
相关标签:
2条回答
  • 2021-01-15 11:13

    As David said, Ord() is a so called "compiler magic" (or, as they call it now, "intrinsic" or "pseudo-") function, i.e. not a real function that is called, but just something that uses a function syntax, but is recognized by the compiler as a special construct and turned into code directly. The same is true for e.g. Chr(), Writeln(), etc. They can usually have different and/or multiple types of parameters or return values and sometimes even have additional syntax elements.

    The documentation says, about Ord(X):

    The result is the ordinal position of X; its type is the smallest standard integer type that can hold all values of X's type.

    In Delphi XE7, 'C' is a WideChar, and the return value of Ord('C') will be a 16 bit unsigned type (Word). Smallint is signed type. That is why you get the warning, because you are comparing a signed and an unsigned type of the same size, so the values must be widened to the next larger type (Integer).

    In Delphi 2007, 'C' is not a WideChar, it is an AnsiChar, so the result of Ord('C') is a Byte. There is no need for widening to the next larger type, since Smallint can contain all values of Byte, so both can be promoted to Smallint.


    I agree that the info hint in the editor is deceptive. Ord() does not always return a Smallint, it returns the minimum type that is needed to hold all values of the argument.

    0 讨论(0)
  • 2021-01-15 11:15

    Ord() is an intrinsic function that yields an unsigned type. Hence the warning. In your case, you are passing it a WideChar, and so the matching integral type is Word.

    0 讨论(0)
提交回复
热议问题