The with statement serves to access the elements of a record or object or class, without having to specify the element’s name each time. The syntax for a with statement is
_________________________________________________________________________________________________________
With statement
___________________________________________________________________
The variable reference must be a variable of a record, object or class type. In the with statement, any variable reference, or method reference is checked to see if it is a field or method of the record or object or class. If so, then that field is accessed, or that method is called. Given the declaration:
The following statements are completely equivalent:
and
The statement
is equivalent to
This also is a clear example of the fact that the variables are tried last to first, i.e., when the compiler encounters a variable reference, it will first check if it is a field or method of the last variable. If not, then it will check the last-but-one, and so on. The following example shows this;
The output of this program is
Showing thus that the X,Y in the WriteLn statement match the T record variable.
Remark: When using a With statement with a pointer, or a class, it is not permitted to change the pointer or the class in the With block. With the definitions of the previous example, the following illustrates what it is about:
The reason the pointer cannot be changed is that the address is stored by the compiler in a temporary register. Changing the pointer won’t change the temporary address. The same is true for classes.