C gotchas and mistakes for C++ programmers [closed]
If y开发者_C百科ou 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 enum
s 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.
精彩评论