An Error Using Records
Watch Out for This Error
Possible Error with Arrays of Records
- Watch out for a subtle error!
- Consider this code:
e: Employee;
elist: EmployeeList;
begin
...
e := elist(i);
e.salary := e.salary + raise;
print(e.salary);
print(elist(i).salary);
...
What gets printed?
Have we changed the Employee in the array?
Solution
e: Employee;
elist: EmployeeList;
begin
...
e := elist(i);
e.salary := e.salary + raise;
elist(i) := e;
// Both show a raise
print(e.salary);
print(elist(i).salary);
...
Solution 2:
elist: EmployeeList;
begin
...
elist(i).salary := elist(i).salary + raise;
print(elist(i).salary);
...
Same Error Occurs with Nested Records
- Consider the line example:
l: Line := ( (1, 2), (3, 4) );
p: Pair := l.p2;
begin
p.x := 99;
put(l.p2.x); // What is printed
Now in Java (assuming the required constructors):
Line l = new Line(new Pair(1, 2), new Pair(3, 4));
Pair p = l.p2;
begin
p.x := 99;
S.o.p(l.p2.x); // What is printed
Underlying this Error: Reference vs Value Semantics
- What's in the array?
- In Java, the array is an array of Employee references
- In Ada, the array is an array of Employee values
- What happens when we assign an element from the array to and
Employee variable?
- In Java: the variable is assigned a copy of the reference
- In Ada: the variable is assigned a copy of the Employee
- What happens when the variable is changed
- In Java: the object referenced by the variable is changed,
changing the object in the array
- In Ada: the object contained in the variable is
changed; the Employee in the array is unchanged