Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the major differences between C and C++ and when would you choose one over the other?

For those of you with experience with both, what are the major differences? For a newcomer to either, which would be better to learn? Are there situations where you might choose C but then other situations where you would choose C++? Is it a case of use the best tool for the job or one is significantly better than the other. I know C++ is an "enhancement" of C, but it was created in '83 and hasn't completely replaced C so there must be something more to it.

I know this question is subjective and I am not trying to start any religious war, so please try to be as objective as possible. Clear strengths and weaknesses and comparisons.

like image 905
Ryan Guill Avatar asked Jan 14 '09 14:01

Ryan Guill


2 Answers

While C is a pure procedural language, C++ is a multi-paradigm language. It supports

  • Generic programming: Allowing to write code once, and use it with different data-structures.
  • Meta programming: Allowing to utilize templates to generate efficient code at compile time.
  • Inspection: Allows to inspect certain properties at compile time: What type does an expression have? How many parameters does a function have? What type does each one have?
  • Object oriented programming: Allowing the programmer to program object oriented, with sophisticated features such as multiple inheritance and private inheritance.
  • Procedural programming: Allows the programmer to put functions free of any classes. Combined with advanced features such as ADL allows writing clean code decoupled from specifics of certain classes.

Apart from those, C++ has largely kept compatibility with C code, but there are some differences. Those can be read about in Annex D of the C++ Standard, together with reasons and possible fixed to make C code valid C++ code.

like image 167
Johannes Schaub - litb Avatar answered Sep 19 '22 14:09

Johannes Schaub - litb


C++ is 99% a superset of C. It's a little more strict in syntax, with a few very minute differences in terms of things changing.

The biggest difference is that C++ makes an attempt at being object oriented. There's native support for classes.

There's a few other perks in C++: templates, stream operators, pass-by-reference (a bit less confusing than pass-by-pointer)

What do you lose out for going C++? It's missing some of the lowest-level hacks that a lot of people use C for. I don't remember any of them offhand, but I've never heard any good argument for tricking the compiler into doing what you want except as a way to push efficiency that extra 10%.

like image 31
user54650 Avatar answered Sep 18 '22 14:09

user54650