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:

  1. The zeroval function takes an int parameter. In Dart, integers are immutable and passed by value, so changes to ival inside the function don’t affect the original variable.

  2. The zeroref function takes a List<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.

  3. In the main function, we first call zeroval, which doesn’t change the original value of i.

  4. Then we create a list iref containing i, call zeroref with this list, and update i with the modified value from the list. This simulates passing by reference and allows us to modify the original variable.

  5. Finally, we print the hashCode of i. In Dart, we can’t directly print memory addresses like in some other languages, but hashCode provides a unique identifier for the object.

When you run this program, you’ll see output similar to:

initial: 1
zeroval: 1
zeroref: 0
hashCode: 0

This 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.