4 ms·
You can write bad code in any language. Frankly the example you linked isn't a great read either. Without being a C++ expert, I wouldn't trust the comment there
by jstimpfle 5y ago
You can write bad code in any language. Frankly the example you linked isn't a great read either. Without being a C++ expert, I wouldn't trust the comment there - are you sure the (unsafe) "rv[skip]" can't be reordered before the ("safe") "rv.at(skip)"?
The right way to handle this might be to interpret the data as unsigned, or to handle a negative value by bailing out.
- jeffbee 5y agoThere's a lot going on here that could be improved, for example the compiler could decide that it's going to just elide the whole thing about `skip + 1 < skip` on platforms with signed char, because signed overflow is UB. My point was that in languages that aren't as primitive as C your function contains mainly just the dangerous logic, and you can read and reason about it. In the C version, it's full of noise like checking calloc return value for null, manually freeing locally-allocated memory, moving data with memcpy instead of just assignment, etc.
- jstimpfle 5y agoYes, local allocations are a pain to maintain. But it doesn't have to be that way. You can always attach allocations to a structure and have them freed in a central place. Personally I'd rather think about what this code should do and would then think how to write in C. The big difference with C++ is the implicit stuff it does - RAII and exceptions. I have a distaste for those, and while I agree it often makes code shorter, the code also becomes more script like, it's putting some important things under the rug. For plain C, there are very elegant ways to improve most code by thinking more globally.