C++ for Wireless Sensor Networks - c++

Similar to: Why are RTOS only coded in C, but:
Besides the numerous myths about C++, why is it not used as much as C/nesC (TinyOS) for WSN? Knowing C++ can be used for Simulating Wireless Sensor Networks with OMNeT++ it is hard not to think that it can also be used in real-time embedded systems as C is to accomplish event handling.
I do NOT want to start a C++ is better than C flame war, but enough evidence suggests that the whole C is faster and more versatile than C++ is a total myth. Take a look at:
C vs. C++ paper where the following points were highlighted:
- C++ is slower than C: Wrong! Many C programs are valid C++ programs as well - and such a C program should run at identical speed when translated with either the C and with the C++ compiler.
- C++ specific features give overhead: Wrong! The so-called overhead introduced by certain C++ specific features (such as virtual function calls or exceptions), is comparable to the overhead you yourself would introduce should you choose to go thru the pain it would be to implement a similar feature in C.
- C++ is object oriented: Wrong! The C++ language contains some language extentions over C, that make object oriented programming and generic programming more convenient. C++ does not force object oriented design anywhere - it merely allows for it if the programmer deems OO feasible. C allows for object oriented programming as well, C++ only makes it simpler and less error prone.
Why are you still using C

I believe the answers to the following question apply here.
Is there any reason to use C instead of C++ for embedded development?

Related

When will using C subset of C++ be bad?

I am currently joining a new project in C++, but I am only acquainted with C. I will look to learn the STL and BOOST, but in the meantime, I foresee myself only programming in the C subset of C++.
My question is, when will just using the C subset of C++ and compiling with the C++ compiler be notably worse than just compiling with a C compiler?
I ask mostly in performance (things like size of executable are not a concern, as we are not working in embedded systems).
I ask mostly in performance
I would say that this is the wrong metric to use. Many C++ compilers share their codebase with C compilers. That is, if a given block of code is valid C and valid C++ (with the same semantics in both languages), the object code produced by the C compiler is likely to be comparable to – if not the same as – that produced by the C++ compiler (ignoring C++ name mangling).
A better metric for "bad" is robustness. The differences between C and C++ are more than syntax. C++ is object-oriented, using a different mindset than C. Given a piece of code that happens to be valid in both languages, the style will often reveal which language it was written as. Thanks to object-orientation, C++ code promotes more robust practices than exist in C (whereas C has a better focus on raw speed). Perhaps the simplest such practice to grasp is RAII.
So the question of "bad" should not focus on the object code, but on the source code. What will your colleagues on this project think of your coding style? You might be better served by learning C++ philosophy before worrying about learning all of the Boost and STL APIs. (There is overlap in what you would learn, so the distinction is not cut-and-dried. Please allow me this bit of exaggeration to make a point.)
Using the common subset of C and C++ is good and in fact necessary, when writing a header that is designed to be usable from both C and C++.
Limiting oneself to C conforming code when writing a C++ source file, and correspondingly limiting oneself to C++ conforming code when writing C source file is unnecessary and leads to code that would be considered poor quality by majority of programmers.
Think of C++ as an extension of C to facilitate object-orientated programming.
C++ contains higher-level features (virtual functions, shared_ptrs, dynamic casts etc) designed to make programming easier, but with the tradeoff of some performance overhead.
These C++ features are built on top of C fundamentals (pointers, malloc etc). So you could avoid virtual functions by using C pointers to functions, but you increase the chance of bugs and readability and maintainability decrease.
So, your C code shouldn't be slower than C++ (unless you do something silly). However, your C++ could be slower until you learn how the C++ features are implemented "under the hood".

Which languages will call C++ with no explicit bridging?

While developing a new product, we decided to go for a mix of C++ and C#, haven been told that bridging them to allow the C# code to call the C++ code would be easy (spoiler, it's not).
We're pretty experienced C++ programmers and not at all C# programmers so we pretty much just had to believe what we've read. A few attempts to call C and Objective-C was promising and we even found a few articles that showed how to make an unmanaged C++ class available in C# -- or at least we thought. The C++ code in the articles, wasn't C++, but instead the horrible monster C++/CLI that Microsoft seems to think is C++. Since we're doing the C# stuff to get some bits "for free" in macOS and Windows, C++/CLI isn't an option either :-(.
Anyway, plenty of people have claimed that it's easy to call C++ code from some specific programming language, but so far, I haven't seen a single one that will allow me to do so (I haven't been paying too much attention to this, so please provide me with an obvious example). C++ invariably always means C with no C++ stuff at all; no namespaces, classes, no stl, lambdas or anything. Just plain dumb C.
So, are there any languages, besides C++(/CLI) that will allow me to do the following:
Create an instance of a class, using a C++ constructor, and dispatch it with a C++ destructor.
Call member functions on an object ( foo f; f.foo();) with a C++ class.
Use std::vector, std::find_if, std::string and other stuff from the stl. Complete coverage of the stl is not required.
Use overloaded functions (i.e. f(), f(int), f(std::string))
Use overloaded operators (foo operator + (foo, foo))
Use C++11, C++14 and/or C++17 features.
Use RAII (rather important IMHO).
Use namespaces.
No. There is no such language.
Unless you count Objective-C++. But that falls pretty much in the same bucket as C++/CLI, in being C++ with some extensions. And C++/CX is another such beast.
There are some interop tools that can work with C++ classes (SWIG for example), but I have never heard of a tool that is capable of instantiating C++ templates (like vector or find_if) on demand.
What languages will call C++ with no explicit bridging?
The short answer to this question is: NONE
Remember that a programming language is a specification written in some technical report, usually in English. For examples, read n1570 (the spec of C11) or R5RS (the spec of Scheme). For C++, see n3337.
Actually, you are interested in implementations, e.g. in compilers and interpreters for your programming languages. These implementations are practically software. And then the answer might become: it depends (notably on the ABI used & targetted by your compiler and system).
See for examples this list of ABIs for Linux.
plenty of people have claimed that it's easy to call C++ code from some specific programming language,
The C calling conventions are quite common, and it might help to declare every C++ function callable from outside as extern "C". But there is no silver bullet, and details matter a lot.
So, are there any languages, besides C++(/CLI) that will allow me to do the following:
list of C++ features skipped
Probably not.
You probably need at least to understand more about memory management approaches. I recommend understanding more about garbage collection, e.g. by reading the GC handbook (at least for underlying concepts & terminology). Learn more about foreign function interfaces (in some cases, the libffi might help) and language bindings.
You might also consider generating some of the C++ or C glue code, maybe with SWIG (or write your own C++ glue code generator).
On operating systems providing dynamic linking capable of loading plugins at runtime (e.g. Linux with dlopen(3)/dlsym(3); but other OSes often have similar facilities) you could even consider generating some C or C++ glue code at runtime in some temporary file, compile it as a temporary plugin, and dynamically loading that plugin. You could also consider JIT-compiling libraries like GCCJIT or LLVM (or libjit).
I recommend reading SICP, the Dragon Book, and probably Lisp In Small Pieces. Of course, learn something about OSes, e.g. Operating Systems: Three Easy Pieces. Reading about Linkers and Loaders could also help.
As an excellent example of cleverly gluing C++, look into CLASP and see this video.
But whatever approach you take, you'll need a lot of work (years, not weeks).
C++ as a language does not have a defined ABI (Application Binary Interface) - which basically means that there is no universal standard of what a C++ class/function call/template would look like in binary form on any given platform, or across platforms.
What that means is that there is no universal way to call C++ code from other languages, on different platforms, or even across compilers on the same platform. It also means that the people who are telling you "it's easy to call C++ code from XYZ language" are mostly incorrect (or at least incredibly incomplete).
Where there are interfaces it's either because the provider of the interface controls the ABI (C++/CLI with .NET), or because there is a translation layer from C++ to something like the C calling convention (Boost::python).
Some work has been done towards attempting to define an ABI per-platform (http://open-std.org/JTC1/SC22/WG21/docs/papers/2014/n4028.pdf), but as far as I'm aware it has not yet been accepted into C++17.
You can look into using C++ interpreter, which allows for the fine-grained control you ask for. But I don't know of any that "just works", see also:
Have you used any of the C++ interpreters (not compilers)?

correct me if my understanding of c++ is wrong

correct me if any of my following current understanding of c++ is wrong:
C++ is an extended version of C. Therefore, C++ is just as efficient as C.
Moreover, any application written in C can be compiled using C++ compilers
C syntax is also valid C++ syntax
C++ is at the exact same language level hierarchy as C.
Language Level Hierarchy
eg. lowest-level: assembly language,
high-levels: Java, PHP, etc
so my interpretation is that
C++/C is at a lower level than Java,PHP etc since it's closer to hardware level (and therefore because of this,it's more efficient than Java, PHP, etc), yet it is not as extreme as assembly language....but C++/C is at the same level with each other and neither one is closer to hardware level
If you start with code that's legal as both C and C++, it will typically compile to the same result with both, or close enough that efficiency is only minimally affected.
It's possible to write C that isn't allowable as C++ (e.g., using a variable with a name that's the same as one of the key words added in C++, such as new). Most such cases, however, are trivial to convert so they're allowed in C++. Probably the most difficult case to convert is code that uses function declarations instead of prototypes (or uses functions without declarations at all, which was allowed in older versions of C).
See 2 -- some syntactical C won't work as C++. As noted, it's usually trivial to convert though.
No, not really. Although C++ does provide the same low-level operations as C, it also has higher-level operations that C lacks.
C++ is at the exact same language level hierarchy as C.
Language Level Hierarchy
eg. lowest-level: assembly language, high-levels: Java, PHP, etc
Programming languages are often categorised from 1st generation (machine code), 2nd generation (assembly language), 3rd generation (imperative languages), 4th generation (definition's a bit vague - domain-specific languages intended for high productivity, e.g. SQL), 5th generation (typical language of the problem expression, e.g. maths notation, logic, or a human language; Miranda, Prolog). See e.g. http://en.wikipedia.org/wiki/Fifth-generation_programming_language and its links.
In that sense, C and C++ are both 3rd generation languages. (As Jerry points out, so are PHP, Java, PERL, Ruby, C#...). Using that yardstick, these languages belong in the same general group... they're all languages in which you have to tell the computer how to solve the problem, but not at a CPU-specific level.
In another sense though, C++ has higher level programming concepts than C, such as Object Orientation, functors, and more polymorphic features including templates and overloading, even though they're all ways to organise and access the steps for solving the problem. Higher level languages (i.e. 5GL) don't need to be told that - rather, they just need a description of the problem and knowing how to solve the entire domain of problems they find a workable approach for your specific case.
C++/C is at a lower level than Java,PHP etc since it's closer to hardware level (and therefore because of this,it's more efficient than Java, PHP, etc), yet it is not as extreme as assembly language....but C++/C is at the same level with each other and neither one is closer to hardware level
This is confusing things a bit. Summarily:
C++ and C do span lower than Java/PHP, yes.
C++ and C do tend to be more efficient, yes. You can get a general impression of this at http://benchmarksgame.alioth.debian.org/u64q/which-programs-are-fastest.html - don't take it too literally, it depends a lot on your problem space.
C++ and C both go as low as each other, but C++ has some higher level programming support too (though it's still a 3GL like C).
Let's look at a few examples:
bit shifting: Java is designed to be more portable (sometimes at the expense of performance) than C or C++, so even with JIT certain operations might be a bit inefficient on some platforms, but it may be convenient that they operate predictably. If you're doing equivalent work, and care about the edge cases where CPU behaviours differ, you'll find C and C++ leave operator behaviour for the implementation to specify. You may need to write multiple versions of the code for the different deployment platforms, only to end up getting pretty much the same performance as Java (but programs often know they won't exercise edge cases, or don't care about the behavioural differences). In that respect, Java has abstracted away a low-level concern and could reasonably be considered higher level but pessimistic.
C++ provides some higher level facilities such as templates (and hence template metaprogramming), and multiple inheritance. Compilers commonly provide low level facilities such as inline assembly and the ability to call arbitrary functions from other objects/libraries as long as the function signatures are known at compile time (some libraries work around this limitation). Interpreted (e.g. PHP) and Virtual Machine based (e.g. Java) languages tend to be worse at this.
Java also provides some higher level facilities that C++ lacks - e.g. introspection, serialisation.
Generally, I tend to conceive of C++ spanning both lower and higher than Java. Put another way, Java overlaps a section in the middle of C++'s span. But, Java has a few stand-out high-level features too.
PHP is an interpreted language that again abstracts away some low level concerns, but generally fails to provide good facilities for more abstract or robust programming techniques too. Like most interpreters, it does allow run-time evaluation of arbitrary source code, as well as run-time modification of class metadata etc., which allows a high level, powerful but dangerously unstructured approach to programming. That kind of thing isn't possible in a compiled language unless the compiler is shipped in the deployment environment (and even then there are more limitations).
C++ is an extended version of C. Therefore, C++ is just as efficient as C.
Generally true.
Moreover, any application written in C can be compiled using C++ compilers
C syntax is also valid C++ syntax
There are some trivial differences, e.g.:
in C++, main() must have return type int and implicitly returns 0 on exit if not return statement's encountered, but C allows void or int and for the latter must explicitly return an int
C++ has additional keywords (e.g. mutable, virtual, class, explicit...) that are therefore not legal C++ identifiers, but are legal in C
Still, your conception is essentially true.
1/4 and 2/3 seem to be saying very similar things, but:
Yes (Depends on what you mean by "extended", but at a broad level, yes)
Not always
Not always
Yes
Moreover, any application written in C
can be compiled using C++ compilers
Not every C program can be compiled using a C++ compiler. There are some differences between C and C++ (keywords, for example), that prevent mixing C and C++ in some ways. Stroustrup adresses some important points in C and C++: Siblings.
C++ is an extended version of C.
Therefore, C++ is just as efficient as
C.
That depends on the language features you use. I heard that using OOP might bring more cache misses than using a more C-like approach. I can't tell wether this is true or not, as I didn't read more on that subject. But it might be something which should be considered. This is only one example were performance isn't easy comparable.
This isn't exactly true, beyond extra C++ language features that are slower, there are different optimizations that can be done that will change this. Due to the better C++ type system, these are actually normally in C++'s favor however.
No, a big case is that C++ doesn't support automatic cast from void* so for instance
char* c = malloc(10); // Is valid C, but not C++
char* c = (char*)malloc(10) //Is required in C++
Except for C99 and newer C features, I think this is nearly always the case. Keep in mind this is only taking into account syntax this doesn't mean that everything that can compile in C can also compile in C++.
Could you elaborate on what you mean by this, what do you mean by "language level hierarchy"?
Summary:
True.
Dangerously false.
False.
Subjective
Some examples for 2/3:
sizeof 'a' is 1 in C++ and sizeof(int) in C.
char *s = malloc(len+1); is correct C but invalid C++.
char s[2*strlen(name)+1]; is valid (albeit dangerous) C, but invalid C++.
sizeof (1?"hello":"goodbye") issizeof(char *)` in C but 6 in C++.
Attempting to compile existing C code as C++ is simply invalid and likely to produce dangerous bugs even if you hunt down and "fix" all the compile-time errors. And writing code that's valid in both languages is perhaps a reasonable entry for a polyglot competition, but not for any serious use. The intersection of C and C++ is actually a very ugly language that's the worst of both worlds.
Your understanding is wrong in some of your points:
1) your first point is right.C++ is an extension of c.
2) second point is right . C can be compiled using c++ compilers.
3) Some of C syntax varies from c++. In c++, using structure , c should specify structure name but c++ it is not mandatory to specify structure name.Also C++ have the concept of class that is not available in c. C++ also have higher security mechanisms.
4)C is procedural language but c++ is object oriented approach. so c++ is not at the exact same language level hierarchy as c.
C language is not a subset of C++ lanaguage. Check the C99 spec for example - it will not compile in C++ compiler easily. However most of C89 source code can be copied&paste to C++ source code.
C and C++ are languages that can be implemented with "zero overhead" comparing to bare iron.
No. But most of C++ compilers are C compilers too. It means that you can compile .C and .C++ files using the same toolchain.
No, The evolution of these languages differs. See answer to question 1.
C++ is multiparadigm language. Yes, it can be used in the same way as C. But it can be used as DSL too - it provides greater abstraction level.
That's a whole big question to answer.
Not in all cases!
not true because of 3
not true
They are not exactly the same
I don't think language level hierarchy matters too much for a thing. For example, C is a high-level one compared to assembly language while it's a low-level one compared with Java/C#.

Why would someone use C instead of C++? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Why artificially limit your code to C?
I started off with learning C, but then jumped straight into C++ simply because it supports OO and was also required for subsequent work. However, some companies insist on employing people with particularly strong C experience - and I've noticed this applies especially to hardware driver development companies.
C string handling is very different than C++ typical string code. Certainly I wouldn't want any C++ string near my drivers!
More specifically, in good, modern C++ you don't really have to understand pointers and handle buffers at low level; but these are basic and crucial skills in device driver code.
Yes, it's possible to write good drivers in C++; but that C++ would really look like C with a few extra features. Most of the C++ library has no place in deviceland.
It could simply be that they do not have a C++ compiler for the platform they are working with... Personally I would always use C++ in preference to C.
C is much more portable - under the current level of standardization of C++, it simply can't be used when portability is important. It is also very hard for C++ code to be integrated (in a reliable and portable manner) into a C environment.
A lot of embedded systems such as microcontrollers, PLCs, etc use C and not C++ because they don't need to have classes just one giant loop with some functions sprinkled about. Nothing fancy but enough to get the job done in a higher-level language. Since C is more familiar to people than assembly, it works well in ~98% of cases.
I think that the reason is fairly simple, a lot of companies want efficient readable code. C is a fairly easy language to understand and grasp, and for many uses there is no reason to complicate development and code continuity by adding whole new concepts (classes, polymorphism, inheritance, etc) that OO languages make possible but may not be needed.

Why would anybody use C over 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.
Although people seem to like to complain about C++, I haven't been able to find much evidence as to why you would want to choose C over C++. C doesn't seem to get nearly as much flak and if C++ has all these problems why can't you just restrict yourself to the C subset? What are your thoughts/experience?
Joel's answer is good for reasons you might have to use C, though there are a few others:
You must meet industry guidelines, which are easier to prove and test for in C
You have tools to work with C, but not C++ (think not just about the compiler, but all the support tools, coverage, analysis, etc)
Your target developers are C gurus
You're writing drivers, kernels, or other low-level code
You know the C++ compiler isn't good at optimizing the kind of code you need to write
Your app not only doesn't lend itself to be object-oriented but would be harder to write in that form
In some cases, though, you might want to use C rather than C++:
You want the performance of assembler without the trouble of coding in assembler (C++ is, in theory, capable of 'perfect' performance, but the compilers aren't as good at seeing optimizations a good C programmer will see)
The software you're writing is trivial, or nearly so - whip out the tiny C compiler, write a few lines of code, compile and you're all set - no need to open a huge editor with helpers, no need to write practically empty and useless classes, deal with namespaces, etc. You can do nearly the same thing with a C++ compiler and simply use the C subset, but the C++ compiler is slower, even for tiny programs.
You need extreme performance or small code size and know the C++ compiler will actually make it harder to accomplish due to the size and performance of the libraries.
You contend that you could just use the C subset and compile with a C++ compiler, but you'll find that if you do that you'll get slightly different results depending on the compiler.
Regardless, if you're doing that, you're using C. Is your question really "Why don't C programmers use C++ compilers?" If it is, then you either don't understand the language differences, or you don't understand the compiler theory.
I like minimalism & simplicity.
Because they already know C
Because they're building an embedded app for a platform that only has a C compiler
Because they're maintaining legacy software written in C
You're writing something on the level of an operating system, a relational database engine, or a retail 3D video game engine.
Fears of performance or bloat are not good reason to forgo C++. Every language has its potential pitfalls and trade offs - good programmers learn about these and where necessary develop coping strategies, poor programmers will fall foul and blame the language.
Interpreted Python is in many ways considered to be a "slow" language, but for non-trivial tasks a skilled Python programmer can easily produce code that executes faster than that of an inexperienced C developer.
In my industry, video games, we write high performance code in C++ by avoiding things such as RTTI, exceptions, or virtual-functions in inner loops. These can be extremely useful but have performance or bloat problems that it's desirable to avoid. If we were to go a step further and switch entirely to C we would gain little and lose the most useful constructs of C++.
The biggest practical reason for preferring C is that support is more widespread than C++. There are many platforms, particularly embedded ones, that do not even have C++ compilers.
There is also the matter of compatibility for vendors. While C has a stable and well-defined ABI (Application Binary Interface) C++ does not. The ABI in C++ is more complicated due to such things as vtables and constructurs/destructors so is implemented differently with every vendor, and even versions of a vendors toolchain.
In real-terms this means you cannot take a library generated by one compiler and link it with code or a library from another which creates a nightmare for distributed projects or middleware providers of binary libraries.
I take the other view: why use C++ instead of C?
The book The C Programming Language (aka: K&R) tells you clearly how to do everything the language can do in under 300 pages. It's a masterpiece of minimalism. No C++ book even comes close.
The obvious counterargument is that the same could be said of most, if not all, modern languages -- they also can't tell you how to do everything in only a few hundred pages. True. So why use C++ instead? Feature richness? Power? If you need something more feature rich or powerful then go with C#, Objective C, Java, or something else like that. Why burden yourself with the complexities of C++? If you need the degree of control C++ grants then I argue to use C. C can do anything and can do it well.
I choose to write in C because I enjoy working with a small, tight language. I like having access to a standard which can be read in a reasonable amount of time (for me -- I'm a very slow reader). Moreover, I use it to write software for embedded systems for which few desirable C++ compilers exist (like some PIC micro-controllers).
In addition to several other points mentioned already:
Less surprise
that is, it is much easier to see what a piece of code will do do exactly . In C++ you need to approach guru level to be able to know exactly what code the compiler generates (try a combination of templates, multiple inheritance, auto generated constructors, virtual functions and mix in a bit of namespace magic and argument dependent lookup).
In many cases this magic is nice, but for example in real-time systems it can really screw up your day.
I'm used to use C++ for my projects. Then I got a job where plain C is used (a 20 year old evolving codebase of an AV software with poor documentation...).
The 3 things I like in C are:
Nothing is implicit: you see what your program exactly does or not does. This makes debugging easier.
The lack of namespaces and overloads can be an advantage: if you want to know where a certain function is called, just grep through the source code directory and it will tell you. No other special tools needed.
I rediscovered the power of the function pointers. Basically they allow you to do all polymorphic stuff you do in C++, but they are even more flexible.
Linus' answer to your question is "Because C++ is a horrible language"
His evidence is anecdotal at best, but he has a point..
Being more of a low level language, you would prefer it to C++..C++ is C with added libraries and compiler support for extra features (both languages have features the other language doesn't, and implement things differently), but if you have the time and experience with C, you can benefit from extra added low level related powers...[Edited](because you get used to doing more work manually rather than benefit from some powers coming from the language/compiler itself)
Adding links:
Why C++ for embedded
Why are you still using C? PDF
I would google for this.. because there are plenty of commentaries on the web already
Because they're writing a plugin and C++ has no standard ABI.
Long compile times can be annoying. With C++ you can have very long compile times (which means, of course, more time for Stack Overflow!).
If you want your code to be understood by virtually any programmer write in C.
I'm surprised no one's mentioned libraries. Lots of languages can link against C libs and call C functions (including C++ with extern "C"). C++ is pretty much the only thing that can use a C++ lib (defined as 'a lib that uses features in C++ that are not in C [such as overloaded functions, virtual methods, overloaded operators, ...], and does not export everything through C compatible interfaces via extern "C"').
Because they want to use features in C99 that don't have equivalents in C++.
However, there aren't as many C99 features that are useful to C++ as people think at first glance. Variable-length arrays? C++ has std::vectors. Support for complex/imaginary numbers? C++ has a templated complex type. Type-generic math functions? C++ overloaded the standard math functions, causing the same result.
Named initializers? Not in C++, but there's a workaround:
struct My_class_params {
int i;
long j;
std::string name;
My_class_params& set_i(int ii)
{
i = ii;
return *this;
}
My_class_params& set_j(long jj)
{
j = jj;
return *this;
}
template <typename STRING>
My_class_params& set_name(STRING&& n)
{
name = std::forward<STRING>(n);
return *this;
}
My_class_params()
{
// set defaults
}
};
class My_class {
My_class_params params;
public:
My_class(const My_class_params& p) : params(p) { }
...
};
This allows you to write things like:
My_class mc(My_class_params().set_i(5).set_name("Me"));
This is pretty shallow but as a busy student I chose C because I thought C++ would take too long to learn. Many professors at my university won't accept assignments in Python and I needed to pick up something quickly.
Because for many programming tasks C is simpler, and good enough. When I'm programming lightweight utilities especially, I can feel like C++ wants me to build in an elegant supersructure for its own sake, rather than simply write the code.
OTOH, for more complex projects, the elegance provides more good solid structural rigor than would naturally flow out of my keyboard.
Most of the significant features of c++ somehow involve classes or templates. These are wonderful features except for the way the compiler transforms these into object code. Most compilers use name mangling, and the ones that don't do something at least as messy.
If your system lives on its own, as is the case with many applications, then C++ is a fine choice.
If your system needs to interact with software not neccesarily written in C++ (most frequently in assembler, or Fortran Libraries) then you are in a tight spot. To interact with those kinds of cases, you'll need to disable name mangling for those symbols. this is usually done by declaring those objects extern "C", but then they can't be templates, overloaded functions, or classes. If those are likely to be your applications API, then you'll have to wrap them with helper functions, and keep those functions in sync with the actual implementations.
And in reality, the C++ language provides a standard syntax for features that can be easily implemented in pure C.
In short, the overhead of interoperable C++ is too high for most folks to justify.
Oh my, C vs C++, a great way to start a flame war. :)
I think C is better for driver and embedded code.
C++ has some great features that C doesn't have, but many of the object oriented features of C++ can cause monumental coding messes when people write code with non-obvious side-effects that occur behinds the scenes. Crazy code can be hidden in constructors, destructors, virtual functions, ... The beauty of C code is the language does nothing non-obvious behind your back, thus you can read the code and not have to look up at every constructor and destructor and so on. A lot of the problem is bad coding practices by SOME people.
My perfect language would be a combination of C99 plus a minimal subset of safer C++ capabilities that adds ZERO (or near zero) compiler overhead to the binary output. Perfect additions would be class encapsulation and naming concepts of data and functions.
One remark about "just use the subset of C++ you want to use": the problem with this idea is that it has a cost to enforce that everybody in the project uses the same subset. My own opinion is that those costs are quite high for loosely coupled projects (e.g. open source ones), and also that C++ totally failed at being a better C, in the sense that you cannot use C++ wherever you used C.
I haven't been able to find much evidence as to why you would want to choose C over C++.
You can hardly call what I'm about to say evidence; it's just my opinion.
People like C because it fits nicely inside the mind of the prgrammer.
There are many complex rules of C++ [when do you need virtual destructors, when can you call virtual methods in a constructor, how does overloading and overriding interact, ...], and to master them all takes a lot of effort. Also, between references, operator overloading and function overloading, understanding a piece of code can require you to understand other code that may or may not be easy to find.
A different question in why organizations would prefer C over C++. I don't know that, I'm just a people ;-)
In the defense of C++, it does bring valuable features to the table; the one I value most is probably parametric('ish) polymorphism, though: operations and types that takes one or more types as arguments.
I would say that C gives you better control over optimization and efficiency than C++ and hence would be useful in situations where memory and other resources are limited and every optimization helps. It also has a smaller footprint of course.
There's also the approach some shops take of using some of C++'s features in a C-like way, but avoiding ones that are objectionable. For example, using classes and class methods and function overloading (which are usually easy for even C diehards to cope with), but not the STL, stream operators, and Boost (which are harder to learn and can have bad memory characteristics).
Because you're writing for a system where resources are tight (such as an embedded system, or some kind real bare metal code like a kernel) and you want as little overhead as possible.
There's a reason why most embedded systems don't have a C++ compiler - it's not that people don't want one, it's that cramming C++ code into that small a space is task that approaches impossible.
Until some years ago the existing C++ compilers were missing important features, or the support was poor and the supported features vary wildly among them, and so it was hard to write portable applications.
Because of the no standard naming of symbols it is difficult for other languages/applications to support C++ classes directly.
What C needed was a better preprocessor.
cfront was one and thus born c++
I'ld use C, where the 'c++ as preprocessor' would not be okay.
I'm pretty sure, at the bottom of any well written c++ library/framework/toolkit,
you would find dirty-old-c ( or static casts, which is same )