Pointers in Dart
Dart supports references to objects, which are similar to pointers in other languages. However, Dart doesn’t have explicit pointer types or pointer arithmetic. Instead, all objects in Dart are referred to by reference.
Here’s an example demonstrating how references work in Dart:
import 'dart:io';
// This function takes an int by value
void zeroval(int ival) {
ival = 0;
}
// This function takes an integer reference
void zeroref(List<int> iref) {
iref[0] = 0;
}
void main() {
int i = 1;
print('initial: $i');
zeroval(i);
print('zeroval: $i');
// We use a list to simulate a reference to an integer
List<int> iref = [i];
zeroref(iref);
i = iref[0];
print('zeroref: $i');
// In Dart, we can't directly print memory addresses
// But we can print the hashCode of an object
print('hashCode: ${i.hashCode}');
}In this example, we demonstrate the difference between passing by value and passing by reference in Dart:
The
zerovalfunction takes anintparameter. In Dart, integers are immutable and passed by value, so changes toivalinside the function don’t affect the original variable.The
zeroreffunction takes aList<int>parameter. Lists in Dart are objects and are passed by reference. By modifying the first element of the list, we can simulate changing the value of the original variable.In the
mainfunction, we first callzeroval, which doesn’t change the original value ofi.Then we create a list
irefcontainingi, callzerorefwith this list, and updateiwith the modified value from the list. This simulates passing by reference and allows us to modify the original variable.Finally, we print the
hashCodeofi. In Dart, we can’t directly print memory addresses like in some other languages, buthashCodeprovides a unique identifier for the object.
When you run this program, you’ll see output similar to:
initial: 1
zeroval: 1
zeroref: 0
hashCode: 0This output shows that zeroval doesn’t change the original value, while zeroref does modify it. The hashCode is printed to demonstrate how we might identify unique objects in Dart, although it’s not directly equivalent to a memory address.
Remember, Dart manages memory automatically and doesn’t expose direct memory manipulation like some lower-level languages do. This design choice helps prevent common programming errors while still allowing efficient memory usage.