There really is this limitation, but at the same time C is a very smart language and provides a trick as a solution. Some will say that it is gambiarra, others will say that it is a good way to make everything simple and favor the standard use, giving the chance of the exception to be expressed in a way that gives a little more work and the normal (pass array by reference) be expressed simply.
But before you do, make sure the size is adequate. Depending on who is saying will put a limit of 4, 8 or 16 bytes to compensate to make the copy. My experience is that 32 or 64 bytes can be interesting depending on the architecture used. But don’t make it a pattern when the size allows. The copy should be used if it is the correct semantics for the case.
The only way to pass a die of a nonscalar type (compound) by value is when using a structure. By default struct
is copied and only if you use a pointer does it become a reference. Then the solution is to encapsulate the array within a structure.
This brings some extra advantages since it creates an abstraction and does not need to worry about the size of the array. I’ve seen people using this technique even if they end up passing the structure by reference, just so they don’t have to keep reporting the size of the array everywhere in the code since it has a canonical shape of size. Obviously any different size will need a different structure.
One might think this generates a cost to the application, but it doesn’t. It doesn’t take one byte more, nor does it take an extra cycle to process. Of course there is a difference between copying the die and not the pointer, this can make some difference and it is your duty to choose the right one for your situation.
#include <stdio.h>
typedef struct {
char array[16];
} Tipo;
void funcao(Tipo p) {
printf("%zd\n", sizeof(p));
printf("%s", p.array);
}
int main(void) {
Tipo dado = { .array = "teste de array" };
funcao(dado);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
The question is about array.
– Maniero
Yes, and every time q appears "array" and "C++" together in the tags, we have to remember that Std::vector exists
– Cleiton Santoia Silva
Not when the goal is to use one array. I always remember you have the
vector
when the goal is to use a data collection, this question is specifically about the mechanism of array.– Maniero
Normally I also speak of Std::array which is a standard implementation of this encapsulation, but has a lot of advantages https://ideone.com/KpAJXv
– Cleiton Santoia Silva