+ 2
Why are arrays and strings almost always reference data types across different programming languages?
6 Respostas
+ 5
They need memory space and should not be duplicated
+ 4
Isn't that still a bit language-specific, though?
In Python, *everything* is a reference-type, and the type itself regulates if an object can be changed (duck typing, immutability).
In Java, strings also seem to be immutable, while they're referenced internally to prevent huge data copying, right?
Now in C++, strings can even be changed if I get it right (and you'd control mutability rather by const and such).
+ 3
Just imagine if you want to pass an array to a function. The function should create a copy of the array in order to perform operations on it.
Also the above asks for more memory which is completely unnecessary.
So passing by reference helps to prevent a copy of the array being created and also the changes can be directly made on the array itself. Also this way you are not using any new memory.
+ 3
HonFu yes... it is
But concerning arrays and strings -which are often arrays - the case is almost clear.
Sometimes people think a string is mutable as
string =string + "end"
works.
It is tricky sometimes