0

So I hear that using pass by value, copies of the parameters are added to the call stack. Apparently, the stack size on Windows is often 1MB. Obviously though, we can easily pass around data that is far bigger than 1MB between functions/procedures (arrays of primitives/classes/hashmaps/sets or whatever)

So is my understanding of the situation wrong...or are these languages using pass by value for primitive types, but then pass by reference/pass by object model for these other data structures?

Just with a quick google, both Java & JavaScript are exclusively pass by value...so how are you able to pass around data/objects bigger than the stack size in these languages? For example, in JavaScript, it's stated: "For Array the maximum length is 4GB-1 (2^32-1)"

  • This may help: [JavaScript by reference vs. by value](https://stackoverflow.com/a/6605700/902497). JavaScript and Java pass references by value. – Raymond Chen May 05 '22 at 14:11

1 Answers1

1

The difference between "pass-by-reference" and "pass-by-value" is that, in pass-by-reference calling convention, the function can change what the reference points to. In languages that don't support a pass-by-reference calling convention, you won't be able to do this directly; you'd have to simulate it by passing a mutable type that contains a reference to another object.

In pass-by-value, you pass references as values too. So the thing that's allocated on the stack, when you're passing an object that isn't a primitive value, is a copy of the pointer, not a deep copy of the data.

The aspect of this that gets confusing is the thing (or instance) of what you point to, if it's a mutable type, can be mutated.

JasonTrue
  • 19,244
  • 4
  • 34
  • 61
  • Ok, so if there is an array with a billion elements and we pass it into a sort function (in a language like Java or JavaScript), presumably that entire array isn't getting copied to the stack? – RandomUser123 May 05 '22 at 05:17
  • @RandomUser123 in the typcal function call argument-passing cases that I can think of it won't be. I think that may not apply if, for example, if you were using the spread operator. – JasonTrue May 05 '22 at 13:50