6 ms·
C++ incorporates nearly all of C99 directly, save for VLAs, restrict, designated initializers, and a lot of small stuff that won't affect any modern-ish C code
by jcranmer 11y ago
C++ incorporates nearly all of C99 directly, save for VLAs, restrict, designated initializers, and a lot of small stuff that won't affect any modern-ish C code (e.g., no implicit int). VLAs and restrict are explicitly not in C++ because they're somewhat broken (C++14 did add "dynamic arrays" which are VLA-lite, and there's work on a better restrict-like functionality, cf. https://isocpp.org/files/papers/N3988.pdf https://isocpp.org/files/papers/N3988.pdf), while designated initializers does not mesh well with C++ semantics.
In practice, then, C++ without RTTI, exceptions, or the standard library is basically a strict superset of C and C code compiled as such will tend to be legal and identical in semantics. The same cannot be said for C# or Java. Given that C++ has some rather useful features (most notably, the ability to guarantee cleanup even in the face of inattentive developers), the only real valid reason to not be using C++ instead of C is if there's no C++ compiler.
- kazinator 11y ago> C++ incorporates nearly all of C99 directly, save for VLAs, restrict, designated initializers ... In other words, C++ incorporates nearly all of C90, save for that C99 stuff that wasn't copied from C++! (Or not incompatibly copied.)
- asveikau 11y agoI find the lack of implicit conversion from void * really annoying. Any time I see someone cast the return type of malloc in a .c file, I curse C++ and die a little. This sounds like a trivial thing but it very much changes the feel of the language, namely into one where you need to insert pointless casts to satisfy a whiney compiler.
- danieltillett 11y agoWhy the hate over casting malloc? It really is not a huge issue. A related question is why do people use malloc if calloc is available?
- asveikau 11y agoProbably the best reason to hate it is if you didn't include the right headers and malloc is therefore implicitly defined to return int. That creates a bug on most 64-bit compilers where int is 32 bits. The cast will mask the bug. But more stylistically, let's be honest, something like this is way too verbose: struct foo *bar = (struct foo*)malloc(sizeof(struct foo)); I see code like this often, and I think the only explanation I can think of is that people don't know the language well enough to write: struct foo *bar = malloc(sizeof(*bar)); > A related question is why do people use malloc if calloc is available? Seems like a very different question... calloc multiplies, calls malloc, and zeros. I guess if you don't want to multiply, don't want to zero, don't want to bother specifying another parameter, some combination of these, then malloc might be a better choice. Though I do recall a few years back the OpenBSD folks (possibly others too?) focusing on making sure calloc checks for overflow when it multiplies. [See also: reallocarray]
- danieltillett 11y agoIf you turn on wall you should be warned that you didn’t include the right headers? I was under the impression that lots of implementations of malloc actually call calloc under the hood. Unless you are calling malloc in a tight loop I can’t see the extra step of zeroing being a issue. In one of my programs where performance is critical I changed over all my mallocs to calloc and couldn’t measure the time change - I did find I had fewer difficult-to-duplicate bugs though. Edit. Interestingly CERT recommends casting [1]. Seems to solve a much worse issue than forgetting to include stdlib.h 1. https://www.securecoding.cert.org/confluence/display/c/MEM02-C.+Immediately+cast+the+result+of+a+memory+allocation+function+call+into+a+pointer+to+the+allocated+type https://www.securecoding.cert.org/confluence/display/c/MEM02...
- kazinator 11y agoAny decent C compiler has a warning for the situation that an external function is called without a prototype declaration having been seen. GCC also has diagnostics for when a function definition occurs without a declaration. From GCC man page: -Wmissing-prototypes (C and Objective-C only) Warn if a global function is defined without a previous prototype declaration. This warning is issued even if the definition itself provides a prototype. The aim is to detect global functions that fail to be declared in header files. -Wstrict-prototypes (C and Objective-C only) Warn if a function is declared or defined without specifying the argument types. (An old-style function definition is permitted without a warning if preceded by a declaration which specifies the argument types.) -Wimplicit-function-declaration (C and Objective-C only) Give a warning whenever a function is used before being declared. In C99 mode (-std=c99 or -std=gnu99), this warning is enabled by default and it is made into an error by -pedantic-errors. This warning is also enabled by -Wall.
- sjolsen 11y ago>it very much changes the feel of the language, namely into one where you need to insert pointless casts to satisfy a whiney compiler You could use the exact same argument against any type-safety feature: inserting "pointless" forward declarations, inserting "pointless" const qualifiers, etc., to "satisfy a whiney compiler." The thing is, implicit conversion from void* is plainly unsound, type theoretically speaking. It has certain advantages, but is not necessary in order to have those advantages. For example, it makes use of malloc easier, but one could also make the vast majority of uses of malloc easier with something like #define ALLOC(TYPE,N) ((TYPE*)malloc(N*sizeof(TYPE))) Or at least, one could if C had a remotely regular type syntax and/or actual type genericity. In contrast, you actually can write template <typename T> T* alloc(std::size_t n) { return static_cast <T*> (malloc (n * sizeof (T))); } in C++, and it's even straightforward to add additional logic like overflow detection. Mark it inline and stick it in a header, and it's effectively the same as the above ALLOC macro, except that it actually works. Now, contrast int* array = malloc(256*sizeof(int)); with int* array = alloc<int> (256); The C++ expression is simpler. Now, if you change the type of the array, but forget to change the allocation expression (for whatever reason; maybe you're using the absurd convention of declaring all your variables before you start initializing and using them): char* array = malloc(256*sizeof(int)); // vs char* array = alloc<int> (256); You get a type error with the C++ version, and the C version silently compiles. Not too much of an issue in this case -- you'll just waste a bunch of memory -- but go from char to int instead of int to char, and now you've got buffer overflows. As for the argument made elsewhere in this thread that explicitly casting the result of malloc in C can mask the fact that malloc has been implicitly delcared, that's a language bug -- one that was fixed more than fifteen years ago.
- asveikau 11y agoYes, I'm glad that you can use templates to re-implement operator new [] in a way that is susceptible to integer multiplication overflows. In all seriousness though, I really mean it when I say I intellectually understand the C++ fan's response to a number of these issues. It took me a long time of writing C but I do understand the template-nerd habitat, and can acknowledge its strengths and use those tricks when working in a .cpp file. What frustrates me is to see the rigidity with which it is followed, and the failure to understand the world in a different way. There is a different world out there that doesn't mind an implicit conversion from void pointers, and they're not "wrong".
- comex 11y agoYou partially countered the parent's second sentence, but didn't address the first. The real reason to use C over C++ is if you want your codebase to retain the positive effects of following C's coherent philosophy. True, as you say, C++ can be made into almost a superset of C, and thus sticking to a small subset of C++'s additional features is a real possibility - in fact, I think it should be more common. But nobody does that, perhaps because of the difficulty of enforcement, because it would seem aesthetically messy, or perhaps because the people who aren't conservative enough to want to stick with C almost unchanged have mostly switched to C++ "proper". I don't know, but here are some of the reasons I stick with C. My interpretation of how C benefits from its philosophy: - Name explicitness: in C, every function in scope at the same time should have a unique name, written out in full. This means that even without much context, such as in a diff (I think there's a quote by Torvalds related to this), or with context but without advanced IDE tools, there's no confusion as to what function is being called. C++ violates this rule starting with the simple feature of method dot syntax - where the namespace for methods depends on the type of the receiver, which may be declared in some totally different location - moving on to overloads, where which overload is selected may depend on several arguments and implicit conversions and defaults and templates, which collectively can be scattered all over the codebase - never mind all the advanced stuff. The resulting code can be more succinct, but is often less clear. Now, there may be some functions which are just so common to type, and/or which have variants acting on different types that act so similarly, that even a philosophy rejecting overloading in general may want to accept it for them. That's sort of what <tgmath.h> was for, and now _Generic lets you make your own; you don't need the entire C++ template system for that. (In a sense, C itself violates name explicitness when it comes to struct field names, since different structs can have fields with the same name. Old fashioned C code uses globally unique names for fields, though presumably more due to feature-challenged early compilers than any philosophy. It has the benefit of making it possible to '#define my_field my_union.foo[0]' etc.) - No implicit function calls: As you mention, destructors are pretty useful as a safety feature, and I think it would be nice to use them in C, but C++'s copy constructors and copy assignment operators and regular constructors and implicit conversions make it very easy to execute some code you didn't really want or need, without indication in the code that something expensive is happening. For example, implicit copies caused by creating std::strings was noted last year to cause a huge number of unnecessary allocations in Chromium: https://groups.google.com/a/chromium.org/forum/#!msg/chromium-dev/EUqoIz2iFU4/kPZ5ZK0K3gEJ https://groups.google.com/a/chromium.org/forum/#!msg/chromiu... - 'Mechanical sympathy': C's inability to override operators like + and [] has downsides (see below), but it does make it more clear what code lowers down to basic machine operations and what code may result in expensive algorithms being run. Compare the performance of + on integers to + on strings. - Mechanical sympathy regarding code size: C++ templates make it very easy to bloat binary code size for minimal or negative runtime performance gain. Not that not having them at all is better, exactly, but C binaries tend to be a lot smaller... - Simplicity -> easier to learn. Explicitness -> harder to muddle along with an understanding that's sort of right but not quite, which has upsides and downsides. - Simplicity -> predictability for advanced users. The C spec is small enough that you can get to a point where you can read C code and almost always know what the standard says about what it should do. There are some confusing parts of the manual that get posted around on the Internet as puzzlers, like integer promotion rules, undefined behavior, sequence points, etc. - and if I were designing a language from scratch, I'd take a hatchet to these sections and pick something easier to understand. But the number of such parts is one or two orders of magnitude lower than in C++. Think function and template overload resolution rules, or the many types of construction, or the many random features which few know about because nobody uses... - Resembles a "post-OOP" language due to being pre-OOP: these days it seems to be popular for languages to encourage things like: -> composition over inheritance -> using more dumb structures to store aggregate data rather than making everything a class with manually written constructors/getters/setters, hidden fields, invariants, etc. Well, C has no inheritance, and it has long made it easy to use dumb structures. In particular, if you wanted to be able to use a struct value as an expression rather than declaring a separate variable, in C++ you had to use a constructor: 'Foo(a, b, c)' - which means that even if you didn't really want any behavior in your struct, you had to manually write a constructor to forward the parameters to the corresponding fields. In C99, you could write (struct foo) {a, b, c} without any boilerplate. Now in C++11 there is Foo { a, b, c } - which solves this problem at the expense of making initialization rules even more complicated. And some of the biggest elements that are less about philosophy than lack of coherent design on C++'s part: - The entire development of the template system as a metaprogramming tool, using a sort of purely functional pseudo-language, is just awful. The whole thing is incredibly complex not as a requirement to provide sufficient power, but because it evolved out of a feature set that was never intended for that use case - in fact, is famously Turing complete by mistake. SFINAE in particular is a horrible hack that makes you do things like add a default argument that will never be specified, and defaults to a class that doesn't do anything except not exist in some cases, and expect the compiler to just silently go along with this - at least concepts will improve that someday. The template system is also just not as nice as macros for a lot of code-generation-like tasks, despite the enormous amount of effort spent on it, and the standards committee's (justifiable) hate for the latter. - Move constructors and rvalue references implement some nice functionality, but the way they're bolted on adds a ton of complexity to the type system and more boilerplate to write for your classes, and the magic that makes things like std::forward work is needlessly confusing. - constexpr is a mess, since a large fraction of functions in general could hypothetically qualify for constexpr, but putting it everywhere would be noisy. There are other issues with it. - Since C++ classes evolved from C structs, all the fields are specified in the declaration, which goes in the header file, even though some of them are private and logically belong to the implementation. A full list of fields is necessary in C++'s traditional compilation model if you want to make instances on the stack, but many classes are heap-only, where having sizeof be a link-time rather than compile-time constant would be no big deal. This results in unnecessary dependencies on .h files leading to longer compile times. In C you can use forward-declared structs for this in most cases; in C++, achieving "PIMPL" requires the sort of workaround code that lives up to the name. - Poor compilation speed is mainly caused by putting everything in header files, which in turn is caused by C++ trying to retrofit features that are useful, but whose implementation would properly involve the linker - template specialization and aggressive inlining - into C's compilation unit model. Maybe modules will solve this when they're standardized in C++20 or whatever. - Another problem caused in part by not involving the linker: the difficulty of C++ ABI compatibility on most platforms. It's naturally trickier than C due to the increased use of library types and the need to match specializations across library boundaries, but it doesn't have to be as hard as it is. - Another is that C++'s overloadable and namespaceable function names have to go through an ABI-dependent mangling process to generate a fake C-compatible name like "_ZTVSd" - which most people can ignore, but for low-level users can be annoying. - By the way, a knock-on effect of lack of simplicity is that the same code usually compiles slower in C++ mode than in C mode, though this isn't a big deal. ...I may as well acknowledge why I don't think C is the future: [..continued in reply..]