Const vs const var
Original Reporter info from Mantis: Erling
-
Reporter name: Erling Johansen
Original Reporter info from Mantis: Erling
- Reporter name: Erling Johansen
Description:
The current fpc supports const declared parameters, for example:
procedure p(const i: integer);
The integer is passed by value and the net result is local constness of i. This is all ok, but perhaps of limited value. If a const parameter isn't a small type (<= 8 bytes), then it is passed by reference. Again, this is all ok, however, the change in parameter passing is at low level, i.e it is an optimization which works because local constness imply global constness. The parameter passing at high level is still pass by value.
What's needed is some way to indicate constness and pass by reference, for example:
procedure p(const var x: AnyType);
The point is that const now deals with constness only and has nothing, at high level, to do with the actual parameter passing at low level.
Const var does not solve every problem on the planet, but it would be useful for interfacing, e.g. in the macos x universal interfaces, because the current use of const alone requires compiler dependent ifdef'ing in user land that isn't elegant and pascal like, and replacing const in the interfacing with var alone removes the read only requirement. Const var would at least solve this problem.
Critique: some would say that const var is meaningless because var indicates the intent to modify a variable. But this is not true. Var indicates that the actual parameter must be a variable and that the formal identifier stands for that variable. Wirth writes in "Programming in Modula-2" about value parameters, that "we must keep in mind that since the formal parameter represents a local variable, storage is needed for that variable. This may be of concern, if its type is an array of many elements. In this case, it is recommended to specify a variable parameter, even if this parameter is used for the import of values only."
The const var is then simply a way to indicate readonly import of values (either because that is how some interface works or to avoid local copies of large collections of values).
Const var should not break existing code, i.e it is not necessary to change the semantics or anything else for const alone, it can continue to work as it does.
Const var should be relatively easy to implement as it can work as const alone, except that small parameter optimization must be skipped when const is followed by var in order to implement true call by reference.
Mantis conversion info:
- Mantis ID: 7612
- Version: 2.2.0
- Fixed in version: 2.6.0
- Fixed in revision: 16180 (#07bf4451)