C gotchas and mistakes for C++ programmers [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.
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.

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.

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.

Why is C++ compatible with 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.
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.

C++ or C++0x - Which is a better standard? [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 12 years ago.
So I've been trying to do some research and would like the opinions of other developers on this topic. I am an experienced C++ programmer and have been using the current C++ standard for some time. I have been reading articles that "C++0x will undoubtedly become the new standard." How far off are we does everyone think from making the switch to a whole new programming standard? Also, which, in your eyes, is a better standard? From how I understand it, C++0x will come with more standard libraries making development easier without many more dependencies. Please help me to catch up!
Thanks!
Dennis M.
It would be pretty sad if the next version of C++ were quantitatively worse than the current one. The entire point of the new revision is to improve things.
Well, it depends.
The current C++ standard (C++03) is currently "better" because most of the latest C++ compilers and standard library implementations conform fairly well to the standard. Yes, there are issues, but most of them are very well known (e.g., hardly any compiler supports export) or are fairly easy to work around.
Support for C++0x is pretty patchy right now. Different compilers support different parts and there have been pretty major modifications made to it over the last year, so compilers that did provide early support for some features are now "buggy" if you consider their conformance to the latest drafts.
Going forward, though, C++0x will be a huge improvement over C++03. Major features like the concurrency memory model and the standard threads and atomics libraries are extremely important for the future of the language. Move semantics will make it easier to write clean, high performance code. Most of the new language features will make developing in C++ a more enjoyable experience.
"C++0x will undoubtedly become the new standard" is an understatement. C++0x is the draft of the new standard. Parts of it are available now in compilers like G++ 4.5.
It is impossible for C++0x to be qualitatively worse than the current C++ standard, because one of the essential things about the new standard is that it is fully backward compatible. If there are bad parts, you can just avoid them. (Of course, that doesn't mean that new features in C++0x can't be used to create really bad code that you'll have to deal with, but if you're coding on your own, you can always choose to avoid C++0x features that are worse in your opinion.)
Depends on what you mean by "better". If you mean "More likely to work with whichever compiler I'm using at the moment", then the old standard will certainly be better, with a little boost thrown in.