How does the Length() function in Delphi work?

后端 未结 5 1638
太阳男子
太阳男子 2020-12-31 13:32
  • In other languages like C++, you have to keep track of the array length yourself - how does Delphi know the length of my array? Is there an internal, hidden integer

5条回答
  •  执念已碎
    2020-12-31 14:17

    There are three kinds of arrays, and Length works differently for each:

    • Dynamic arrays: These are implemented as pointers. The pointer points to the first array element, but "behind" that element (at a negative offset from the start of the array) are two extra integer values that represent the array's length and reference count. Length reads that value. This is the same as for the string type.

    • Static arrays: The compiler knows the length of the array, so Length is a compile-time constant.

    • Open arrays: The length of an open array parameter is passed as a separate parameter. The compiler knows where to find that parameter, so it replaces Length with that a read of that parameter's value.

提交回复
热议问题