Using the `in` keyword causes “E1012 Constant expression violates subrange bounds” in Delphi

怎甘沉沦 提交于 2019-12-05 13:08:00

问题


I've come across some rather unusual behaviour in a bit of Delphi code. When using the in keyword to check if an item is in a constant array, I get the following compilation error:

E1012 Constant expression violates subrange bounds

The constants are defined as follows:

type TSomeEnum = (seFoo = 1000,
                  seBar = 2000,
                  seBoo = 3000,
                  seFar = 4000,
                  seFooBar = 5000,
                  seBooFar = 6000,
                  seLow = 1000,
                  seHigh = 6000,
                  seCount = 6);

The line that is failing is the following:

if someObj.someProperty in [seFoo, seFar, seFooBar] then
...

Whilst I understand the reasoning behind the error showing in another question posted here, where bounds checking on integer arrays wasn't done at compile time when using a variable, it seems odd that I'm getting the same problem with a constant array which is most certainly within bounds.

For now, I've replaced the line with a (much larger) statement comprising of or clauses. However, this is clearly not ideal. Can anyone shed any light on why I'm getting this problem?


回答1:


Documentation about Sets says :

The base type can have no more than 256 possible values, and their ordinalities must fall between 0 and 255.

So even if you can have enums of any value, the if xx in [a,b,c] statement will fail here, since a set cannot hold a value larger than 255.

Use a case statement instead:

case xx of
  a,b,c : // Make something 

end;


来源:https://stackoverflow.com/questions/12181617/using-the-in-keyword-causes-e1012-constant-expression-violates-subrange-bound

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!