3 ms·
You can’t pass an array by value and you can’t pass a pointer with a corresponding length of non-fixed size (you can actually with VLAs, but frankly the syntax
by david2ndaccount 3y ago
You can’t pass an array by value and you can’t pass a pointer with a corresponding length of non-fixed size (you can actually with VLAs, but frankly the syntax sucks and not all compilers support it). This missing language feature has led to horrible things like nil-terminated strings , a million bespoke ways to encode the length of the array, or just functions that pray you have enough space like `strcpy` and `gets`.
- tpoacher 3y ago> You can't pass an array by value Sure, but, this is the case in all languages, no? Otherwise, what should be the convention? A deep copy? A first-degree shallow copy? You simply can't avoid the referential nature of arrays for use as arguments to functions. So the issue here shouldn't be the referential nature of this, but the fact that they chose to implement it as a "decaying" pointer as opposed to a "pointer to array type of a certain size". And hence why I'm pointing out there is, in fact, a (relatively simple) way to do this, but only for fixed sizes. But the reason it's not THAT useful in practice is because, in general, you probably wouldn't want the function's parameter to expect a fixed size array, but you'd probably want the flexibility of a variable-sized array, whose length is defined at runtime. And this is what is not supported by c. So in some sense, in the absence of support for variable-sized array parameters, then not expecting fixed array sizes at the point of defining function parameters, and using a decaying pointer instead (which simply doesn't care about the size), is probably the lesser evil of the two. So for me the 'bigger' evil isn't decaying pointers, but the lack of support for VLAs as function parameters. This would have allowed you to use the above syntax to pass a pointer to an array type, retaining full information about the pointed array, including its size. (in other words I think we're saying a very similar thing but with different words)