I’m testing some snippets I found off the web using g++ from MinGW. This is the C++ compiler…why then does it correctly compile C….why do people intertwine C and C++.
The concrete question is: Is it O.K. to use both C and C++ and compile under g++. If the answer is yes, this makes my life easy as I do not have to modify the code.
Oddly enough…to get some C++ to work, particularly when passing a string to an ifstream constructor it requires a C type string…
My guess would be that because C++ depends upon C constructs at times is is O.K to write the two languages together.
However as a matter of style you should settle on cout/cin or printf/scanf.
There are a few oddities where
char*is needed. You can bridge the gap by using the.c_str()method of astd::stringto get one.For the most part, the C subset of C++ is compatible. Exactly how it isn’t compatible is not likely to matter for the most part:
http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B
If you’re compiling snippets of C code under a C++ compiler, be sure to change it to use the “c” lib format in your includes…for example
#include <cstdio>instead of#include <stdio.h>Is it bad practice to use a C header instead of its C++ equivalent in C++ (e.g. stdio.h instead of cstdio)?
For a fairly reasoned argument from Bjarne himself on why to avoid scanf, check out the beginning of this paper:
http://www.stroustrup.com/new_learning.pdf
There are a lot of benefits to using iostreams instead of printf as well:
'printf' vs. 'cout' in C++