3

There is any way of making x array constant after the data is read from user? There is any way of making variable not modifiable after it's value is read from user (eg. y)?

program hmm;
    uses crt;
    var 
        i, y: word;
        x: array of word;
begin
    readln(y);
    y:=y-1;
    SetLength(x,y); 
    for i := 0 to y do begin
        read(x[i]);
    end;
readkey;
end.

To make y constant I tried something like this, but it won't work - y will be set as 0.

program hmm;
    uses crt;
    var 
        i: word;
        x: array of word;
    const
    {$J+}
        y:word = 0;
    {$J-}
begin
    {$J+}
    readln(y);
    y:=y-1;
    {$J-}
    y:=0;
    SetLength(x,y); 
    for i := 0 to y do begin
        read(x[i]);
    end;
readkey;
end.

Thanks for help.

Isinlor
  • 1,111
  • 1
  • 13
  • 22

1 Answers1

3

Yes. Don't change either of them in your code after you set the initial value.

Other than that, there's no way. A dynamic array by definition is changeable, and so is a variable - that's why they have dynamic and variable as names.

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • So it's also quite silly, to not say stupid :/. IMHO there should be a way of assigning value of constants at the run-time, not only before compiling, but can you tell me why {$J+} and {$J-} don't work? – Isinlor Nov 06 '12 at 17:10
  • I have no idea why they don't work; I've never used them. As far as your question, I didn't say it was silly or stupid; if I'd thought that, I would have downvoted and voted to close instead of answering. There's no need to write to constants, ever, IMO. Just accept the input from the user once, and then never write to the variables again in your code. That's very easy to enforce (it **is** your code, after all), and when you pass around the variables to other routines define the parameters as `const SomeVar: Integer` and it can't be changed in the receiving code at all. – Ken White Nov 06 '12 at 17:36
  • BTW: The only reason, AFAICT, that there is still support for the ridiculous "writeable constant" at all is support for legacy code; it's been obsolete since Delphi 2 was released (and `{$J+/-}` were introduced). – Ken White Nov 06 '12 at 17:39
  • 1
    @Non - What matters is the state of the switch at the place of the declaration of the constant, a constant is either writable or not for its life time. – Sertac Akyuz Nov 06 '12 at 20:42