Why choose C instead of C++ or C++ instead of C?

Asked

Viewed 17,889 times

82

I think everyone with the least amount of knowledge knows when to choose C or C++ over other languages. There are clear cases where these languages are more suitable and others that do not make so much difference. But there may be a situation where you know that one of the two is ideal but you don’t know which one.

What concrete elements we should look at and in which situations we can be sure that C is more appropriate than C++ or C++ is the most appropriate?

The reasons need not be essentially technical but they need to be objective, needs to be something experienced professionals in both languages usually agree.

In other words, which problems C handles best and which C++ usually does well?

Of course, both can be used for any project, but it is not always the most suitable tool. There are cases that some requirements may make a choice impossible. What requirements can make it so difficult to use one language that it is better to use the other?

Consider policy points as not fundamental requirements, only the technical part really matters.

  • Those who don’t understand C and C++ development don’t know what makes each one more attractive or not.

  • Excellent question! I’m starting my studies with C++ now, let’s clarify this question.

  • I never stopped to think about it... but if what C does, C++ does too, then using C++ seems to be more advantageous since I can get as close to OO as possible, which wouldn’t be possible in C... Correct?

  • @sergiodeveloper is not that simple. Even because OO is usually bad, but it’s not worth talking about here (it’s something that few, truly experienced, programmers understand).

5 answers

74


I will answer the question by pointing out some facts and advantages over languages. Make the choice on your own:

  • C can be compiled on any architecture.

    One of the first things that happens when a new architecture appears is the creation of a compiler for the C language (perhaps based on an existing compiler, just adding a new one target). The point is that whatever architecture you find, it’s pretty much guaranteed that you can write a program in C and compile it. This is because C is a "simple" and quite low-level language. C++ is immensely more complex and is likely to find architectures that do not yet have language support.

    However, it must be said that this difference between languages is less and less significant as compiler collections become more widely used. For GCC or Clang (LLVM), for example, you can add a new backend that compiles the compiler-specific intermediate representation for your target architecture and immediately supports all languages (frontend) that the compiler supports. When it comes to microcontrollers, GCC supports many of their architectures, so it is perfectly acceptable to write a program in C++ instead of the usual C.

  • C is faster than C++

    Lie! This is a more historical myth than anything else. The fact is that C++ compilers are much more complex than C compilers, so it is difficult to apply optimizations to transformations that benefit speed. But today’s compilers are much better than yesterday’s compilers and that difference is largely overcome. The affirmative actually reverses. C++ has features that allow you to write code more efficiently than in C while maintaining the elegance. Observe templates and functions constexpr as an example. But of course, in C++ you have many high-level resources that would be less efficient than dealing with the simplest implementation. Of course it’s less efficient to use std::regex instead of writing a parser processing a const char* at hand. But everything that can be written in C, can be written in C++ with exactly the same efficiency. There are only advantages.

  • C has a well-defined ABI within each system

    Both Linux and Windows define a C API for applications to use. Along with this, they also define an ABI, an Assembly way of passing the arguments to these functions of the system and naming them. Thus any compiler will use the same mechanism as the operating system to write the passage of arguments and the nomenclature of the internal functions of the code. This means that given any binary library, I can load a symbol and call it as a function with the confidence that I’m doing it right.

    In C++ there is no well-defined convention on this, each compiler uses a different ABI and it is not difficult to see different versions of the same compiler using a different ABI to accommodate some new feature. So it is much more complicated to write an interface for C++. Most scripting languages, for example, only accept native extensions that have been written in C (or C++, but export an interface in the C form).

  • C is universal

    You can compile C for almost any architecture. In any environment you will get a stable ABI. So, if you want to make a tool that generates portable code, using C as output is perfectly acceptable. Note the Bison as an example. Still, I would advise you to take a look at what the LLVM has to offer in this regard. You generate LLVM-style Assembly (not as low as real machine assemblies) and it produces an executable on the target platform. That’s what Clang does.

  • C++ provides resources at zero cost

    A C++ motto is zero overhead, zero overload. If you don’t use a certain feature, you don’t pay for it. This principle ensures that language is full of resources, but at the same time, it is as fast as you want it to be. Just avoid some key points such as RTTI (run-time type Identification), polymorphism or exceptions. The language can also work without the operating system, just don’t use the standard library and write it all on your own.

  • C compilers are faster and spend less memory

    True. Generally compiling a program in C is faster because it is a simpler language. The main reason C++ code is heavier to compile are templates. They produce a large amount of additional specialized functions that need to be inline and optimized. In addition to compile-time calculations via constant expressions. Anyone who has compiled anything that includes boost to say so. Anyway, this is rarely a decisive reason to choose one language over the other, but a point to consider in very large projects.

  • C is the most used in open source projects

    This is more of a primarily historical factor. By 20 or 30 years, when most of the major projects we see today were crawling, C++ was not as popular and C++ compilers were much lower than C compilers for quality and performance issues. So going to C was a natural choice. And today converting a project of this size to a different language is a monumental task, but not impossible. With C++ it is possible to write much cleaner, modularized and organized code, the advantages are many. However there is still a great and irrational resistance the use of C++.

  • C is obsolete. C++ is the substitute.

    Another mistake. C and C++ are different languages, although they share parts in common. Each has its use. But none of them are dead. New revisions and updates are created regularly, keeping them modern. As an example, in 2011 both gained native thread support. Another point to make clear is that not every C code is valid C++ code, especially the conversion between pointer types. In C there are even features that have not yet reached C++, such as the keyword restrict, mentioned by @luiscubal in the comments, although most compilers support as an extension.

  • I never imagined Linus saying such a thing. I don’t know why but I remembered the SOEN when reading his link, rsrs.

  • Note that C may not be faster than C++ if we write the same code in both, but if we compare idiomatic C code with idiomatic C++ code there can already be differences.

  • Additionally, C supports restrict and C++ does not. This has implications for the types of optimizations that can be done. By contrast, C++ has exceptions in the language, so compilers can optimize error situations in a way that would have to be manual (and probably slower) in C.

  • 1

    @luiscabral, can you give me an example? And please, comparing apples with apples, equivalent resources.

  • @Guilhermebernal Of what? Of idiomatic, of restrict or of more efficient exceptions?

  • 1

    @Guilhermebernal By the way, it is "luiscubal", not "luiscabral". If you write "@luiscabral" I do not receive the notification.

  • @luiscubal Ops, cellular autocorrector. I’m curious about the improvement in performance that the restrict allows (I didn’t study in depth the novelties of the C11). What about the idiomatic example you thought.

  • 3

    @Guilhermebernal restrict has been added to C99. Consider a function void f(int* A, int* B) { for (int i = 0; i < 10; ++i) { A[i] *= B[0] } }. In this case, access to B is constant so it could be extracted from the loop. But what if B = A? Or B = A + 1? The compiler has to take this into account, so this optimization is disabled (or at least a Runtime check is added at the beginning of the function).

  • 4

    @Guilhermebernal An example of idiomatic code C vs C++ are the strings. In C, it is idiomatic to use const char*. In C++, the idiomatic is to use std::string. If I want to access the string size, I use strlen or size. But one is linear complexity, the other is constant. That is, when we go into idiomatic examples, we start to do different things (sometimes without realizing it) and the comparisons end up being apples with apples. It is true that C strlen is as slow as C++ strlen, but in C++ strlen is not recommended, so it is not fair to make the comparison like this.

  • 1

    @Guilhermebernal The example of strings is in favor of C++, but I could probably find a favorable example for C. But what matters is the general idea.

  • Bjarne Stroutrup (creator of C++) himself said that C is an obsolete language.

  • Could address "myth or truth" to "C++ has all the standard language and library features that C has, otherwise it doesn’t happen".

Show 7 more comments

14

C and C++ belong to different architectures*

Despite the possibility of using the structural paradigm C++ (c++ is multi-paradigm), however it is not possible to use the OO paradigm (in all its amplitude because it is possible to store a pointer to a function within a struct (making a half-falsified object)) in a programme written exclusively in C.

There are a lot of Apis dedicated to providing a C interface++

There are a lot of Apis dedicated to providing an interface with C++, I have had to use Apis focused exclusively on C++ (and not C) like the Tesseract OCR.

C++ is far more powerful than C

C++ is much more powerful than C with regard to functionality due to the fact that it is a C extension Wikibooks, author Robert W. Sebesta in his book of programming language concepts exposes the range of resources that C++ has (even in structural paradigm).

C is a little faster than C++

It is possible to notice a slight extra performance of programs written in C, comparative benchmarks can be found in benchmark.

C and C++ are at different levels* Some authors consider C to be a mid-level language while C++ is considered an auto-level language because it has object orientation, has more advanced features and a greater distance from the machine, here comes an observation se C++ é um superconjunto de C então ela também pertence ao mid-level.

7

I understand that there are two main factors affecting choice:
1) the libraries to be used in the project, and;
2) Mastery of language;

Libraries are a determining factor. Many projects use ready-made libraries and must include third-party class declaration modules. Thus it is more practical that the project is developed in C++. To isolate the access to objects defined in classes there will be an extra effort.
In the case of development in Windows environment, using access to modules with COM/Activex interface does not make sense to use ANSI C, since the work to adapt the calls to the requirements of this technology will require great technical difficulties.

Driver development has factors that make it suitable for using C. Its features, for example, allow your code to be contained strictly in its source, with dependencies limited to system API calls. Modules with minimal external dependencies tend to be candidates to use C as a development language. Many small embedded systems use C-language restricted compilers, forcing their choice.

Feeling comfortable using a language is a determining factor. Therefore, mastering the technology affects the choice of language. Some of the facilities offered by C++ are in my view very attractive compared to the pure C. Being able to declare variables at any point in the code or guarantee release of resources using classes are some.

  • 1

    Declaring variables anywhere in the code is possible in pure C since C99...

4

My answer to your question would be:

Only use C++

With the following caveat: unless there is some reason why you are thank you using C...

What would be those reasons?

  1. the lack of C++ compiler for the target platform;
  2. restrictions on the target platform, such as problems in implementing the exception handling; or
  3. lack of knowledge of the language C++.

Remember that C++ is almost a superset of the C language, that is, virtually all programs or libraries written in C will run unchanged in C++, generating exactly the same code.

  • 4

    Bold and "Only" suggest a lot of restriction for many caveats.

  • There is only one caveat; the numbered items are examples of motifs that fall under the caveat.

  • 3

    In making such a restrictive statement, make if necessary a more in-depth argument about the benefits or harms of what is being compared.

  • 2

    -1 Saying "only use C++" does not help, not a bit more than saying "only use C". Mainly because, although there are many things you can do in C++ that you can’t do in C, there are also many ways you can introduce yourself bugs code using seemingly simple elements of C++, such as destructors.

  • I’d say the exact opposite. Give preference to C, which is a smaller, simpler language; only consider C++ if one of the C++ Features is worth it. This is basically applying the "less is more" rule, where we choose the minimum necessary to achieve a goal satisfactorily.

0

In my opinion and being very direct:

C you use when you need something lower level, something closer to machine language. When you need to use more machine resources in a specific way to your problem, as in an embedded project for example.

C++ is a high-level language, with the highest abstraction power. With it it is possible to use object orientation, which facilitates system development. Often, common day-to-day systems

I hope I’ve helped ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.