-1

this parameterized swapping function in DART is not swapping the original values when called.

`void main() {
  int var1 = 10;
  int var2 = 20;
  swap(var1, var2);
  print(var1);
  print(var2);
}

swap(var1, var2) {
  var1 = var1 + var2;
  var2 = var1 - var2;
  var1 = var1 - var2;
}`

The output should be 20,10 but it remains 10, 20.

Rishabh Bhardwaj
  • 365
  • 1
  • 5
  • 11

1 Answers1

1

Primitives (like int, bool, and num) are passed by value. But in the case of an object, the reference of the object is passed. This is the same behavior as in Java for passing arguments. So the values won't swap in main().

Sanjay Sharma
  • 3,687
  • 2
  • 22
  • 38
  • Everything is passed by value. The value of a non-primitive object is a reference to it. In a true pass-by-reference system, `var o = Object(); someFunction(o);` would be allowed to make `o` refer to a completely different object (rather than must mutating the existing one). – jamesdlin May 29 '20 at 18:31
  • In other words, the primitive vs. non-primitive distinction doesn't matter. The `swap` function wouldn't work with non-primtiive types either. – jamesdlin May 29 '20 at 18:34
  • If it's an object and you change the value like `o.x = y` and `o.y=x` in `swap()` then the changes will be visible in `main()`'s `o`. Isn't it?. That's called pass by reference. – Sanjay Sharma May 29 '20 at 18:35
  • No, that is not pass-by-reference. Compare to C++ for a true pass-by-reference system. – jamesdlin May 29 '20 at 18:36
  • I didn't use C++ recently but I think you are mistaken. Please check [this](https://www.w3schools.com/cpp/cpp_function_reference.asp) . Let me know if I'm still wrong. – Sanjay Sharma May 29 '20 at 18:40
  • Yes, you are still wrong. In a true pass-by-reference system, the callee can reassign the *variables* in the caller, not just mutate objects. Also see https://stackoverflow.com/q/25170094/. – jamesdlin May 29 '20 at 18:40
  • This is a completely different way of understanding. yeh, we actually pass the reference of the object in languages like Java or Dart but it's not exactly how it works in C++. – Sanjay Sharma May 29 '20 at 18:45
  • Updated the answer as per the discussion. Thanks :) – Sanjay Sharma May 29 '20 at 18:48