When to use printf/scanf vs cout/cin?
There are a few oddities where char*
is needed. You can bridge the gap by using the .c_str()
method of a std::string
to 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++
The C++ language inherits much of its core functionality from C. That's because C++ was derived from C. The C++ Standard includes, by reference much of the C Standard. Therefore you can use the C++ compiler to write code using C constructs, idioms and paradigms. Doing so is often referred to as using C++ "as a better C."
The long and the short of the above is yes, you can use printf
in C++ code. Doing so is explicitly allowed by the Standard.
Doing this however will often neglect many of the features that define C++. I'll leave that conversation for another question but suffice it to say that many people will tell you simply "don't do that" or "that's not C++." This sets aside the reasons why you might not want to use printf
in a C++ program or indeed why you would want to. But rest assured that it is technically allowed.
Is it O.K. to use both C and C++ and compile under g++.
Yes, it is fine to mix the two languages. This is common with code that started out as C, but then got more and more C++ features added (obviously somebody changed the compiler along the way).
Generally, C code will compile and run with a C++ compiler. There are many possible exceptions, such as use of keywords like class
and virtual
for names of things in C code, or C's relaxed casting rules.
You will often hear people say "they are very different languages". That's because any programming question you ask probably has a different answer depending on which language you're trying to use. However, there are lots of similarities and backwards compatibility aspects as well.