Reputation: 2591
I have a code like this
const
value1 = 1;
value2 = 2;
value4 = 3;
.
.
.
valuen = n;
and say I want to add value3 = 3;
to the list without having to deal with the pain of editing all the values to n.
Is there a intrinsic method or a trick that can be done to make this easier in the future?
Upvotes: 1
Views: 264
Reputation: 34919
Use the Delphi editor.
Step 1: Add the new const variable in its right place:
const
value1 = 1;
value2 = 2;
value3 =
value4 = 3;
value5 = 4;
value6 = 5;
value7 = 6;
Step 2: Use the column block selection shortcut to select from 3 to the end of the list. To turn on column mode selection, press Ctrl+O+C and mark the block. Alternatively, drag the mouse with the Alt key down.
Upvotes: 4
Reputation: 3099
You can use the Succ()
function. Of course, using enumerations are easier to understand, but this is the direct answer to your question.
Example:
const
value1 = 1;
value2 = succ(value1);
value4 = succ(succ(value2));
value5 = succ(value4);
value6 = succ(value5);
To insert Value3
, you have only to change value4
and leave value5
and value6
unchanged.:
const
value1 = 1;
value2 = succ(value1);
value3 = succ(value2);
value4 = succ(value3);
value5 = succ(value4);
Upvotes: 2
Reputation: 28836
No, there is no way to update the values of the consts if they are defined that way and if a new value is inserted somewhere in the middle. But see below: there are ways to achieve this.
But you could use an enumeration instead:
type
ValueType = (
value1 = 1, // 1
value2, // 2
value4, // 3
...
valuen); // n
You can easily add a value3
, and all subsequent values shift accordingly:
type
ValueType = (
value1 = 1, // 1
value2, // 2
value3, // 3
value4, // now: 4
...
valuen); // now: n+1
This also makes them typesafe. Of course, if you really want to use them as integers, you will have to cast: Integer(value3)
(to read or write) or use Ord(value3)
(to read). But you would typically use them directly as enumerations. You can also easily create sets out of these, which is much harder with constants.
Of course, if you really want to use constants, you can do what others do in such circumstances:
const
value1 = 1; // 1
value2 = value1 + 1; // 2
value4 = value2 + 1; // 3
value5 = value4 + 1; // 4
// etc...
Now, if you want to add a value3
, you'll only have to update a few values:
const
value1 = 1; // 1
value2 = value1 + 1; // 2
value3 = value2 + 1; // new: 3
value4 = value3 + 1; // modified: 4
value5 = value4 + 1; // now: 5
// etc...
This is of course less typesafe and requires more work.
For an API that always expects an integral type or even or-ed/and-ed combinations of such integers, and which I can't modify, I would use integral constants again:
type
Flags = Cardinal;
const
Flag1 = 1; // 1
Flag2 = Flag1 shl 1; // 2
Flag3 = Flag2 shl 1; // 4
Flag4 = Flag3 shl 1; // 8
// etc.
Used like:
MyAPIFunc('Hello, world', Flag1 or Flag3 or Flag4);
Upvotes: 3