Recent

Author Topic: Use of constants as array bounds?  (Read 425 times)

darknatter

  • Newbie
  • Posts: 3
Use of constants as array bounds?
« on: November 17, 2025, 11:43:30 pm »
What is wrong with the following? Surely it must be possible to use a constant to specify array specs

const
        NUM_CONTROL_TYPES: Integer = 8;

var
   ControlsByType: Array[0..NUM_CONTROL_TYPES] of Array of TControl;


Err: Can't evaluate constant expression

Thausand

  • Sr. Member
  • ****
  • Posts: 453
Re: Use of constants as array bounds?
« Reply #1 on: November 17, 2025, 11:46:14 pm »
That write able constant (typed constant). That no true constant. Write able constant can have change value runtime. https://www.freepascal.org/docs-html/ref/refse10.html

edit: may be have look here https://www.freepascal.org/docs-html/ref/refsu14.html and have choose static array or dynamic array.
« Last Edit: November 17, 2025, 11:53:24 pm by Thausand »

jamie

  • Hero Member
  • *****
  • Posts: 7486
Re: Use of constants as array bounds?
« Reply #2 on: November 17, 2025, 11:55:30 pm »
What is wrong with the following? Surely it must be possible to use a constant to specify array specs

const
        NUM_CONTROL_TYPES: Integer = 8;

var
   ControlsByType: Array[0..NUM_CONTROL_TYPES] of Array of TControl;


Err: Can't evaluate constant expression
Code: Pascal  [Select][+][-]
  1. Const NUM_CONTROL_TYPES = 8;
  2.  

Problem with that is you can't change the value at runtime because its a compile time value which you have for your array as a static fixed size defind at compile time.

 If you a flexible runtime array, then use a Dynamic Array that can be adjusted at runtime.

Jamie
The only true wisdom is knowing you know nothing

n7800

  • Hero Member
  • *****
  • Posts: 589
  • Lazarus IDE contributor
    • GitLab profile
Re: Use of constants as array bounds?
« Reply #3 on: November 19, 2025, 11:21:35 pm »
@darknatter, in other words, constants don't require a data type:

Code: Pascal  [Select][+][-]
  1. const
  2.   NUM_CONTROL_TYPES = 8;          // "true" const
  3.   NUM_CONTROL_TYPES: Integer = 8; // not "true" const
  4.  

As far as I remember, this was a tweak from old Turbo Pascal for compatibility reasons. When specifying a type, it's like a variable, and a global one at that. You can read more in the links above.

 

TinyPortal © 2005-2018