←back to thread

78 points p2detar | 1 comments | | HN request time: 0s | source
Show context
unwind ◴[] No.46204307[source]
Quite interesting, and felt fairly "modern" (which for C programming advice sometimes only means it's post-2000 or so). A few comments:

----

This:

    struct Vec3* v = malloc(sizeof(struct Vec3));
is better written as:

    struct Vec3 * const v = malloc(sizeof *v);
The `const` is perhaps over-doing it, but it makes it clear that "for the rest of this scope, the value of this pointer won't change" which I think is good for readability. The main point is "locking" the size to the size of the type being pointed at, rather than "freely" using `sizeof` the type name. If the type name later changes, or `Vec4` is added and code is copy-pasted, this lessens the risk of allocating the wrong amount and is less complicated.

----

This is maybe language-lawyering, but you can't write a function named `strclone()` unless you are a C standard library implementor. All functions whose names begin with "str" followed by a lower-case letter are reserved [1].

----

This `for` loop header (from the "Use utf8 strings" section:

    for (size_t i = 0; *str != 0; ++len)
is just atrocious. If you're not going to use `i`, you don't need a `for` loop to introduce it. Either delete (`for(; ...` is valid) or use a `while` instead.

----

In the "Zero Your Structs" section, it sounds as if the author recommends setting the bits of structures to all zero in order to make sure any pointer members are `NULL`. This is dangerous, since C does not guarantee that `NULL` is equivalent to all-bits-zero. I'm sure it's moot on modern platforms where implementations have chosen to represent `NULL` as all-bits-zero, but that should at least be made clear.

[1]: https://www.gnu.org/software/libc/manual/html_node/Reserved-...

replies(1): >>46207599 #
jandrese ◴[] No.46207599[source]

    This:

    struct Vec3* v = malloc(sizeof(struct Vec3));

    is better written as:

    struct Vec3 * const v = malloc(sizeof *v);
I don't love this. Other people are going to think you're only allocating a pointer. It's potentially confusing.
replies(2): >>46208075 #>>46210680 #
f1shy ◴[] No.46208075[source]
I also personally find totally confusing leaving the * in the middle of nowhere, like flapping in the breeze.
replies(1): >>46210662 #
unwind ◴[] No.46210662[source]
Where would you put it? The const of the pointer is not the main point, it's just extra clarity that the allocated pointer is not as easily overwritten which would leak the memory.
replies(1): >>46215310 #
1. f1shy ◴[] No.46215310{3}[source]
I put it attached to the variable name when possible, if not attached to the type.