博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C vs. C++

Posted on 2010-12-24 19:05  天地玄黄  阅读(518)  评论(0)    收藏  举报

Anything you can do in C, you can do in C++. While it's not 100% true that C++ is a superset of C, the exceptions are just tiny corner cases where you have to modify C code slightly to make it work in C++.

The advantages of C++ over C are that there are way more tools available to help you to write more straightforward, more readable code. Work with strings just as easily as integers. Use namespaces to simplify function names without worrying about name collisions. Use templates to have a typesafe way of applying the same algorithm to multiple types. Use private and protected to provide cleaner APIs.

The disadvantage of C++ over C is that the language is enormously more complicated, so it's harder to know exactly what code will do, and seemingly simple operations can have tricky unintended consequences. For example, seemingly innocuous use of templates can cause your code size to explode. Or, c = a + b might do anything in C++ because the + operator might be overloaded, there's no way to know without reading through all of the code. (In C, there's only one addition operator and it can only be used for basic types.) Or, appending one item to the end of a vector might cause the whole thing to be reallocated. Or, you can never be sure if you'll return from a function call, because that function might raise an exception. Finally, the language is so complicated and obscure that it's really really hard to learn the whole thing inside-out - so even experts who have been using C++ for years will sometimes encounter a statement and not know exactly what it does.

People who write operating systems, device drivers, embedded software, and real-time software tend to prefer C, because the code must be utterly reliable and predictable. Every programmer working on the team should be 100% clear on what every line of code does.

C++ is also extremely popular, but many teams who write C++ deliberately choose a subset of the language and disallow the use of some features. This helps reduce the scope of potential problems and allows them to take advantage of C++ without worrying about some of the potential gotchas. For example, some projects disallow exceptions and operator overloading.

If your goal is just to get something done, you might prefer C++. The language simply has more tools available to make your life easier, for example it's much easier to work with strings.

On the other hand, if you want to learn a programming language inside out, so that you can read any code in that language and know what every line does, start with C. You can master C in a few months if you're dedicated, but mastering C++ takes a lifetime.