C++ – Using C Expressions in C++ Code

c

At school we started learning C this year, despite the fact I'm way ahead of class, and I learned Java, C++ and C while the class is at the base of C. Anyhow, I've been documenting myself, reading books, articles, and I've asked my teacher why I should learn C, and she said it was the foundation of C++. When I first started programming I found C++ alot easier, I later on learned C. But In books you can see that C code works in C++ yet it doesn't go vice-versa.

My question is pretty straightforward ~ Is it a good habit to use C expressions in C++? Let me give you an example:

Should this code

#include <stdio.h>
#include <iostream>

int main() {
int x;
scanf("%d", &x);
cout << "The number you entered is " << x << "And it's double is " << x*x;
return 0;
}

Be more efficient or better in any way than this:

#include <iostream>

int main() {
int x;
cin >> x;
cout << "The number you entered is " << x << "And it's double is " << x*x;
return 0;
}

I have already done some easy documentation on this in some dusty old books, and from what I could find, using scanf instead of cout also flushes the stream or something like that, so I'm basically asking if it's better to use scanf and in what contexts.

This also applies to file IO as I've always found FIle IO to be easier in C than in C++. This question goes for pretty much every general expression in C applied to C++. It's also notable that I'm using a modern compiler and nevertheless this should not matter as I'm asking if it's a good programming habit to use C expressions in C++ code.

There are probably cons and pros of doing this, but I'm only looking for a yes/why, no/why type of answer.

Also if there are any details I've left out post a comment.

Best Answer

No, it's a bad habit. When you do this for a living, you'll likely end up violating style guides that your team adheres to (or at least get whacked during code reviews).

Yes it works, but if there's a c++ equivalent, use it. (e.g. try not to mix printfs with couts)

Related Topic