Hacker News new | past | comments | ask | show | jobs | submit login

This was very good!

I was really happy when the first code on the page, for once, did not look like it was written by someone writing C when they would much rather write something else.

This line:

    struct article *my_article = malloc(sizeof *my_article);
Is almost exactly how I would have written it, and (to me) does three things very right:

- Does not use a pointless, wordy, bloated cast to somehow "convert" the pointer to the proper type. The point of malloc() returning a void pointer is that no such cast is needed.

- Does not hardcode a size, but uses the sizeof operator to let the compiler compute it.

- Does not repeat the type name, which is brittle and wordy, but instead (again) lets the compiler compute it from the target pointer.

I was a bit more hesitant about this line, later in the article:

    return (void *)b + sizeof(block_t) + b->size;
Not sure what language standard is targeted by the code in the article, but being able to do pointer arithmetic with void pointers is a GCC extension which at least should be mentioned.



For context, the reason why you often see explicit casts from void* to other pointer types is that C++ forbids implicit casts from void*, which is one of the few compatibility breaks that C++ did with C.

(For better or for worse, people often compile C-style code with a C++ compiler)


> which is one of the few compatibility breaks that C++ did with C

It's not "few" though, it's "quite a lot". C and C++ semantics are so different that you'll have to write in a specific "common C/C++ subset" for code that should compile both in C and C++ mode.

For all the flak that Objective-C usually gets by both C and C++ people it did one thing right: it respects C as a proper subset instead of creating its own bastard-fork like C++ did and then freezing it in the mid-90s.


I know, that's why I wrote that the code looked like it was written by someone who wanted to write in C (as opposed to someone who wanted to write in C++, a different language).


Does anyone know, why does C++ forbid implicit casts from void*?


C++ tries to have a slightly stricter type system than C. The compiler can't check anything when you cast from void*, and since C++ has other mechanisms which usually make casts from void* unnecessary (such as using 'new' instead of 'malloc' for heap allocation), I think it makes sense to require casts from void* to be explicit.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: