5 ms·
Except it has absolutely no type safety whatsoever. With modern-style C++, you can do the same thing in exactly 1 line: std::sort(begin(array), end(array), [
by yuushi 14y ago
Except it has absolutely no type safety whatsoever. With modern-style C++, you can do the same thing in exactly 1 line:
std::sort(begin(array), end(array), [](int a, int b) { return a < b; });
Versus:
qsort(array, MAX_VAL, sizeof(int), compare);
With compare as defined before. I mean, sure, it's just sorting and it's a tiny example, but to me it shows a lot about why I prefer C++ over C: typesafety, readability, reduced possibility of buffer overflows, reduced possibility of segfaults based on incorrect element access, speed thanks to code inlining vs function pointers...
- temujin 14y agoYes, std::sort is better than qsort on simple types, but that's an isolated case. I'm currently working on a major "C++" project where literally the only C++ dependency is std::sort right now.
- tptacek 14y agoI've coded in C since 1993, shipped commercial systems C code from 1996 through ~2004 (with an 3-year C++ interlude in there), and continued to write C code on projects from then today. In that time, the number of bugs I've dealt with due to the lack of type safety on a void* is: zero. Lest you think I'm being cavalier about this, I've been writing professional Ruby since ~2006, and have since then been routinely aggravated by bugs that would have been mitigated by type safety. I buy type safety. But it's a continuum of value, not a core principle of development. In idiomatic C code, void* is a way of dropping in and out of static typing, usually to pass values of arbitrary types to a generic container library or through a callback. The use of void* doesn't surrender type safety throughout the program. Idiomatic C code casts a specific type to void* at the call site of the function that handles generic types, and casts it back to that specific type the moment that library hands it back. Of the arguments C++ devotees marshall against C, I find this one among the fudliest.
- yuushi 14y agoI guess we'll just have to agree to disagree then. Perhaps you are a far more conscientious programmer than many out there; the number of buffer overflow exploits would suggest so. C++ doesn't make you immune to such things, but it does give you the tools to make such things less likely to occur. Further, I like compiler-enforced type safety. For when C was created, utilization of void* was a brilliant idea. Language design has moved on since then, and as much as many people really hate template-based C++ code, I honestly welcome it in comparison.