Alex Rivera | Logout

When to use printf/scanf vs cout/cin?

Asked 2011-10-15T19:22:26.383
8

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.

Edit
Report

1 Answer

3

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.

answered 2011-10-15T19:40:33.147

Your Answer