3 ms·
Yes. int read(int n; int fd, char (&buf)[n], size_t n); is a bit bulky. The initial "int n;" is a little used GCC extension. Allowing int read(int fd
by Animats 8y ago
Yes.
int read(int n; int fd, char (&buf)[n], size_t n);
is a bit bulky. The initial "int n;" is a little used GCC extension. Allowing
int read(int fd, char (&buf)[n], size_t n);
is an option. "n" is used before it is declared, which is strange for C. This is only a problem because of the UNIX idiom that buffer pointer comes before size in most system calls.
char (&buf)[n]
is also a bit bulky, but that, too, is forced by C/C++ tradition.
char &buf[n]
would be an array of refs, and
char buf[n]
would be an array passed by copy.
There have been many, many attempts to "fix" C in a non-backwards compatible way. The result is always a new language. It's the backwards compatibility that's hard.
- loup-vaillant 8y agoHow about eschewing the passing by value altogether? If someone wants to do that, they can memcpy() the array inside the function for no extra syntax. So, the following would mean fat pointer: int read(int fd, char buf[n], size_t n); The following guarantees your array is not modified (but it's still passed by pointer). int write(int fd, const char buf[n], size_t n); The following emulates passing by value: void foo(const int buf[n], size_t n) { int tmp[n]; memcpy(buf, tmp, n); } Alternatively: void foo(const int buf[n], size_t n) { int tmp[n]; arrcpy(buf, tmp); // may or may not check bounds } Maybe this would render the proposition less useful, but it would already help. Here's for instance authenticated encryption from Monocypher, my crypto library: void crypto_lock_aead(uint8_t mac[16], uint8_t *cipher_text, const uint8_t key[32], const uint8_t nonce[24], const uint8_t *ad, size_t ad_size, const uint8_t *plain_text, size_t text_size); It is not crystal clear that `text_size` is referring to the size of both the `plaintext` and the `cipher_text`. With something like your proposition, I could write this instead: void crypto_lock_aead(uint8_t mac [16], uint8_t cipher_text[text_size], const uint8_t key [32], const uint8_t nonce [24], const uint8_t ad [ad_size], size_t ad_size, const uint8_t plain_text [text_size], size_t text_size); That way, the size of each buffer is crystal clear. Bonus: a sanitizer can check that I don't overflow my bounds (and I love sanitisers for stuff as sensitive as a crypto library).