+ 2

Why are arrays and strings almost always reference data types across different programming languages?

31st Jan 2020, 6:54 AM
Raiyan Ahmad Saadi
Raiyan Ahmad Saadi - avatar
6 Respostas
+ 5
They need memory space and should not be duplicated
31st Jan 2020, 6:56 AM
Oma Falk
Oma Falk - avatar
+ 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).
31st Jan 2020, 10:53 AM
HonFu
HonFu - avatar
+ 4
Oma Falk, yeah, in Python, although it may look like you mutate it, you are creating a new object. In C, you can directly manipulate (raw) strings, and also the higher string type of C++ can be changed, it has methods like push_back, pop_back and insert.
31st Jan 2020, 11:09 AM
HonFu
HonFu - avatar
+ 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.
31st Jan 2020, 7:56 AM
Avinesh
Avinesh - avatar
+ 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
31st Jan 2020, 11:03 AM
Oma Falk
Oma Falk - avatar