Why is C++ compatible with C? [closed] - c++

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
After reading an amount of C++ articles and tutorials, I often see the phrase "C++ is not C!" or some variant. If this is true, why is C++ trying to be compatible with C? Surely this just encourages C programmers to write bad C++ code? I'm only a newb in the field, so feel free to bombard me with reasons why I'm wrong in thinking that C++ should just make it's mind up and forget C. Ell.

The purpose of compatibility with C is so that C++ programs can have convenient access to the billions (trillions?) of lines of existing C code in the world. It was never intended as a suggestion to code C++ as if it was C.
Peripheral objectives were:
Leverage the C skills that many programmers have (given that it is still one of the most widely used languages in the world).
Encourage the use of C++ as a better C, for: a) easing the transition to C++, and b) improve C coding practices for programmers who have no intention of going to C++.

You can read the historical perspective from the man himself here.
Should C++ forget C? In a sense it already has, the development of the two languages progress independent of each other.

C++ started as "C with classes", and it was just a precompiler that transformed the class & co. syntactic sugar into C code (C was chosen because it was quite widespread, C compiler were available for many platforms); this was one of the reasons it was (is) C-compatible. Another (and maybe more important) one was to remain compatible with the existing C codebase (libraries, syscall, ...), which has been a significant advantage for its widespread usage.
However, during its evolution and standardization, C++ evolved in something quite different.
All the new features that were packed in it (notably advanced OOP capabilities, exceptions, templates) and the evolution of its standard library (especially the inclusion in it of the STL) encouraged new programming styles, that differ significantly from the old "C with classes" style; many common C idioms became obsolete, and had better replacements in C++ (see e.g. std::string vs C-style strings, std::vector vs "normal" heap-allocated arrays). Still, it wasn't a good idea to remove the "older" features, since (1) C compatibility is still important in many cases, (2) the "old" stuff is the foundation for the C++ data structures (std::vector internally uses raw pointers and plain heap arrays) and (3) the background philosophy of C++ is to let the programmer choose.
Since in general the "native" C++ alternatives are better than (usually safer/easier to use/more difficult to misuse, and in general as fast as) the corresponding C idioms, it's usually told to C++ newbies to forget about C and start directly from C++, to avoid picking "C bad habits".
In particular, many C habits (=> e.g. raw pointers) become dangerous when exceptions are used, so it's better that a new programmer starts from the beginning with the idea that his code can be interrupted at any place, and make it exception safe from the beginning wrapping its resources in RAII classes.

C++ used to be compatible with C (it was even compiled with a C compiler, using preprocessor macros to turn it into C), but then newer versions of C came out, and C++ got it's own compilers, and since then, then languages have become different. Still, with a little care, you can get C code to link properly with C++ code.

Related

Should I update my program from C to modern C or C++? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have an old program written in C from the 1990's. I would like to update it so that it will work for the next persons and on modern compilers. Currently I am using a really old version of TurboC to make changes. Should I be focusing on rewriting this in modern C or C++? Which will be the easiest to bring this code up to date without having to rewrite too much and be able to reuse most of the existing code?
My programming background has mostly been in hprogramming languages like Perl, Python, PHP, Powershell, and Visual Basic, so I am not too familiar with the differences between C and C++.
C and C++ are different languages, not different versions of the same language. Stick to C, although you could use the fancy features of newer versions of the standard, like C99.
Your last sentence pretty much answers your sentiment. If you aren't familiar with the differences and you only know older languages I wouldn't update this program unless there is something horribly wrong with it that is affecting many users.
You could update it just within the C world to adhere to C99 or C11 if you have a newer compiler
Given:
have an old program written in C from the 1990's.
You have two questions:
Should I be focusing on rewriting this in modern C?
Maybe, maybe not. I would try to adhere to a standard C89, C99, or C11. This mainly depends on your tools and how much new development will happen.
Do you like declaring variables other than at the beginning of scope? If so, then possibly update to C99. Are you using any tools that really like C89 and show errors or warnings with C99 conventions? If so, then stick to C89.
If the program is continually being updated and you are hiring young people, then newer conventions might be beneficial.
Should I be focusing on rewriting this in C++?
No.
Most well-written C programs are also valid C++ programs, or require just a little adaptation. The opposite is not true.
It's probably easier to stick with ANSI/ISO C and leave both doors open for the next maintainer.
It's probably about the same effort to move to a modern C compiler vs. a modern C++ compiler. The evolution of C and C++ have diverged where each has similar features but they're not source compatible.
There are a few factors that would lead me to choose to update to C++:
Modern C doesn't seem to enjoy as much support as C++. For example many new things in C seem to get implemented only as required by C++, especially in the Microsoft world. VS doesn't even support C99 except for what's in C++, let alone C11.
C++ is a better C: "C++ is "a better C" in the sense that it supports the styles of programming done using C with better type checking and more notational support (without loss of efficiency)." This is still true of modern versions of C.
C++ adds features that support some very powerful techniques. Really making use of them may be best left to library developers, but that means C++ can support really great libraries.

Why Was the GObject System Created? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
The Introduction
Okay, so after version 0.60 of GTK+, the designers realized that for future development and progress, the entire toolkit needed to be rewritten to be object-oriented.
Now, since C doesn't support OOP, to provide object-orientation and in inheritance heiriearchies, they created the GObject System. Now creating the GObject System must have required development time, more dependencies, more problems, but they had to create it to provide object orientation capabilities to the C Programming Language. But at that time, there was another solution that provided exactly that, C++!
The Question
Why didn't the developers of GTK+ just use C++?
The Explanation
I mean, Why waste time creating an entire library instead of using a time-tested solution adopted by a lot of projects? Don't get me wrong, I am not trying to turn this post into a C vs C++ thing (I've had enough of that on forums, thank you). I just want to know the reasons and issues that made the designers of GTK+ make the decision they did.
I can't directly answer the question, at least as far as GTK goes. That answer lies with the GTK+ developers, so you'll have to hunt them down and ask them. But as for why one would want to add an object oriented system to C, instead of using C++, there are plenty of reasons. The three I would immediately think of are
Language Complexity: While C is a pretty simple language, C++ is mind-numbingly complicated, with support for most (not all) C stuff, as well as conveniences like references, and also object-oriented features and a complex template language. And have you seen the new system of values: lvalues, rvalues, glvalues, prvalues and xvalues - huh? There's plenty more I could talk about. Given time, C++ becomes manageable, but it's still overkill for just wanting some object oriented features in C.
Control: If the designers went with C++, they'd be stuck with C++ philosophy. For instance, multiple inheritance is a controversial idea, and for good reason. By design, the GObject system is built to only support single inheritance, which can drastically simplify the inheritance hierarchies. If the designers went with C++, there would be no way to limit users to a single inheritance system. Multiple inheritance is just an example - I'm sure there's plenty of other places in which the GObject system differs from the C++ ideology.
Interoperability: This is probably a big one. Although there a few languages with which C++ interoperates cleanly, the fact is that C++ just isn't that great at interop. However, interoperability with C is almost taken for granted. C is often described as the lingua franca of programming languages, since it forms the de facto standard for interop. By designing a C API, the GObject designers opened the door to GTK+ development in any number of languages.
GObjects is intended to be language independent. It has dynamic typing, and you should it compare with a run-time system like COM, .NET or CORBA, rather than with specific languages. If you go into languages, then the features are more at the Objective-C than the C++ side.
The GObject type system does things that you can't do in C++. For one thing, it allows creation of new classes at runtime, and does this in a way that is language-independent - you can define a new class in Python at runtime, then manipulate instances of that class within a function written in C, which need not even be aware that Python was ever involved.
From the wiki linked to in the question:
History (From Wikipedia)
GTK+ was originally designed and used in the GNU Image Manipulation Program (GIMP) as a replacement of the Motif toolkit; at some point Peter Mattis became disenchanted with Motif and began to write his own GUI toolkit called the GIMP toolkit and had successfully replaced Motif by the 0.60 release of GIMP.[3] Finally GTK was re-written to be object oriented and was renamed GTK+. This was first used in the 0.99 release of GIMP.
This should tell you that object-oriented paradigm was not a paramount criterion for the choice of language for GTK (which is different from GTK+) and that feature was added much later.

Using C++ but not using the language's specific features, should switch to C? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I'm developing a NES emulator as a hobby, in my free time.
I use C++ because is the language I use mostly, know mostly and like mostly.
But now that I made some advance into the project I realize I'm not using almost any specific features of C++, and could have done it in plain C and getting the same result.
I don't use templates, operator overloading, polymorphism, inheritance... so what would you say? should I stay in C++ or rewrite it in C?
I won't do this to gain in performance, it could come as a side effect, but the idea is why should I use C++ if I don't need it?
The only features of C++ I'm using is classes to encapsulate data and methods, but that can be done as well with structs and functions, I'm using new and delete, but could as well use malloc and free, and I'm using inheritance just for callbacks, which could be achieved with pointers to functions.
Remember, it's a hobby project, I have no deadlines, so the overhead time and work that would require a re-write are not a problem, might be fun as well.
So, the question is C or C++?
If you are making use of even a few of C++ features, I would just stick with C++. The only reason to really avoid C++ would be if you were on an embedded system and had no option. There are a couple of nice things about C++ that makes life easier and more maintainable. Unless of course you want to use this as an exercise to force yourself to learn how to do things in pure C.
One of the design principles of C++ is not to add any overhead for features you don't use.
You say you use "almost none" of C++ features. Just keep using those few features you do like or find useful and don't worry about the rest.
Stay in C++ and utilize its STL containers, even if your application is not built around classes.
I would stick with C, until you feel like there is some feature that you really need in C++ that would be difficult for you to do in C.
The reason is, with C++, it's very easy to get sucked into learning new features so you end up spending a ton more time on C++ than on your NES emulator.
This, in itself, is not a bad thing, if your primary objective is to learn C++. Since learning C++ is not your main focus, and since you are just barely starting out in C++, I would recommend that you stay in C. After all, entire kernels are still being written in C.
(FWIW, I'm primarily a C++ programmer these days, but I started in C).
If for whatever reason you would want to use C instead of C++ you should make the switch now. C is a subset of C++, so if you can do it in plain C I would say go for it. If you decide later that you need some of the ++ that C++ has to offer it would be easier to change the code from C to C++. It's much harder to change from C++ to C.
If you use strings and some kind of containers, C++ and its STL would be best to stay with. Also, C++ is not as lax as C when it comes to conversion, so you may get better (more) warnings/errors when compiling with C++, which is good. Other than that, I wouldn't care.
Staying with C++ you might gain something in the future, and will never lose anything.

Is C notably faster than C++ [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
As far as I understand all scripting languages and core scientific programs are usually written in C; this renders the implementation messy yet in a way straight to the point.
I understand these people would like to max their performance but is there a real difference between using C strings and C structures to using C++ classes; C++ seems to work the same way, apart from virtual functions, it stores a class function once and every instance of that class calls that one function.
What makes C faster and is it a notable difference in a project such as python or sqlite who have to be the fastest?
C++ is often used for scientific programs. The popularity of C may be waning in that domain. Fortran remains popular as a "low-level" language.
In C++, "you only pay for what you use." So there is nothing that would make it any slower than C. In particular for scientific programs, expression templates make it possible to perform some custom optimization using the template engine to process program semantics.
The reason C is preferred for projects such as Python is that it tends to be less confusing to read, so a large codebase will be more accessible to a larger pool of contributors.
SQLite has a requirement for small executable code size, where C does have a slight edge. Judicious use of C++ still allows use in embedded applications, but it is less popular due to fear that unwanted language features will creep in.
I don't think that the reason is so much related to performance as it is to interoperability. The C++ language is more complex than the C language, but from a performance point of view there shouldn't be a notable difference in either way. Some C++ constructs are faster than the C equivalent (std::sort is faster than qsort) and there are probably good examples of the other way around.
EDIT: On the interoperability side...
Basically, the C++ standard does not define some of the things that might be needed for easy interoperability between binaries created with different compilers/versions. The most notable issue here would be the naming convention for the symbols in the binary. In C, the language defines a single mapping from each symbol in code to the binary symbol name. A function called my_function will create a symbol in the binary called my_function. On the other hand, and due to features like function overloading, the names of C++ functions have to be mangled (translated into different function symbols in the binary, encoding the types of the arguments and return types), and the standard does not define how the mangling is performed. That in turn means that the same function in C++ can be compiled to different symbols depending on the compiler (unless extern "C" is used to force C interoperability for those functions in C++).
At the end of the day, the interface between the scripting language and the native code would have to be a C interface anyway, even if the details of how it is implemented internally could be C/C++/any other native language.
(I am intentionally not wanting to enter into a flame war of language prefences, C++ is really powerful, but it is also a bit scary as it is a much more complex language than C, and some things that look simple might have an impact on performance)
As Bjarne mentioned in [D&E] the effectiveness is one of the main goals of C++.
So C++ is slower only when programmer uses its "extra" functions like virtual functions you mentioned, rtt information etc
So I think it is more of psychological reasons - C is used as it doesn't allow "slow" C++ features.
Languages are not inherently faster or slower, interpreters and compilers might be more or less efficient.
Besides that, higher level languages provide abstraction layers that usually have a runtime cost. If you are not using them, the compiler might be smart enough to strip them out, but that might not be possible if the semantics of the language do not allow to do it safely... And if you need them, implementing them by yourself in a lower level language will be probably slower than using the "slow" language.

C gotchas and mistakes for C++ programmers [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
If you are C programmer or C++ programmer that knows C well, can you tell me what are the most common mistakes/pattern/style that you noticed from C++ programmers? For example, do you noticed a difference between a C program written by a C programmer vs C program written by C++ programmer? If you can provide a list specifying the major misunderstandings that C++ programmers tend to have about C, I will really appreciate it.
I want to learn C, but while a C++ background helps, I'm afraid that it might hurt as well. I have this weird assumption that besides some keywords and libraries, I don't have to learn anything else because I know C++. I feel bad about having that assumption because I do recognize that C++ != C, but sometimes the difference get blurry when I use C libraries in C++ or maintained legacy procedural C++ from others.
Btw, I'm not asking what are the C++ features not present in C, or whether we/they use "malloc" and they/we use "new".
Thanks.
One thing that I see happen quite frequently is properly freeing allocated memory. Especially associated with structures containing dynamically allocated memory. With C++, destructors are automatically called and if properly written they take care of the associated objects clean up. With C you have to remember to either free all the memory allocated with a structure, or remember to call some kind of destruct function that does it for you.
I'm not sure I'd call this a "mistake", but an experienced C++ programmer who has to use C is likely to create a lot of things that look like classes and virtual-function tables.
This is not necessarily a bad thing, as you can certainly do object-oriented programming in C, but it may be overkill for a particular problem.
I can't really say from personal experience, but I believe you may potentially encounter some subtle problems with things like references (prepending & to a variable name) as function parameters, how enums aren't fully qualified types like they are in C++, stuff involving memory functions that return void pointers... things like that.
Pretty much, when you find idiomatic C code, then it looks similar to idiomatic C++ code, except you have to hack around all the missing language features and implement your own half-assed version of them. For example, macros -> templates/inline functions. void* pointers-> inheritance. function pointers->function objects. exceptions->goto & error codes.