4 ms·
C/C++ Array Size
- quietbritishjim 7y agoThis isn't a notable enough topic to feature on Hacker News IMO, it's more like a stack overflow answer. Even if it were, to be honest it's a very poor article on the subject: * Mixes up C and C++ in the same article. These languages obviously have a shared heritage and some topics apply to both, but this is certainly a case where they're different enough that separate articles would be better: C has VLAs (actually g++ might also have them as an extension) and C++ has templates and the container concept. * Had discussion of malloc which is basically irrelevant to C++ except for historical discussion or interoperability with C, both of which are irrelevant here. Basically this is a symptom of the previous point. * Doesn't mention that the sizeof(array)/sizeof(array[0]) trick can be put in a macro in C, and usually is, or why this is frowned upon in C++. * Doesn't mention the risk of using sizeof(array)/sizeof(array[0]) on a raw pointer, specifically that array[0] will compile, which would surprise some people. * Doesn't mention that in C++ you can use templates to create a completely safe array size function. * Doesn't mention that the C++ library has such a function in it! If the article is about C++ then this should actually be the leading point, with discussion about how it works as the following content. * Doesn't discuss how that function also works for STL containers, and what error you can expect if you pass a raw pointer to it. * There are more subtleties but I'm on my way to writing a blog post myself here so I'll stop. * On a stylistic note: there is way too much text and code before you get to the actual point, which is hard to find if you don't already know what to look for. And it's jarring to use "please" in instructions, I know it seems like it's being polite but it actually turns a fact (if you want to X then you can do Y to accomplish it) into a request (please do Y). I hope you're the blog author or that was a bit of a waste!