Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question
11  
Be real careful about mixing stdio and iostream. There's certain order and synchronization guaranteed within a family that don't necessarily apply outside it. –  David Thornley Feb 13 '12 at 21:18
    
Thanks for the tip, but that code scrap was a pure example. Thanks anyway. –  Bugster Feb 13 '12 at 21:25
19  
If you are learning Programming; You must learn proper indentation! –  bitmask Feb 13 '12 at 22:02
2  
scanf() isn't a great example; it is so terribly error-prone to use that I would advise you to avoid it in C or C++. –  Russell Borogove Feb 13 '12 at 23:56
1  
It might have been sample code only, but David's comment really gets to the heart of the issue why you should not use C idioms when programming in C++. They're completely different languages; don't confuse them any more than you confuse Java and C, or C++ and Visual Basic. –  Cody Gray Feb 14 '12 at 3:30
show 1 more comment

6 Answers

up vote 31 down vote accepted

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)

share|improve this answer
    
+1 - Short and to the point. And this highlights the main point in my answer that team guidelines help bring people together and unify them so they can work together. –  jmort253 Feb 13 '12 at 21:01
    
This comment pretty much answers my question properly and brings a solid argument. Thank-you. –  Bugster Feb 13 '12 at 21:36
1  
@ThePlan thanks. everyone had great answers for this question. –  jglouie Feb 13 '12 at 21:37
    
Note: using printf consistently will work just as well as using cout consistently. The only problems are mixing them together, and style. –  immibis Mar 8 at 23:47
add comment

In general, C and C++ are looked at as if they are two completely separate languages. Therefore, it may be considered bad form to use C syntax in a C++ program.

You are correct; however, that C code will compile just fine. It really depends on how flexible your company is in terms of following standards. If I were ever asked the question in an interview, I would be sure to let the interviewer know that C works in C++, but also that C and C++ are two separate languages and probably shouldn't be mixed unless there was a very, very good reason for doing so.

Another thing to consider is that standards help create a platform where more people can easily work with code. While you were lucky to have a teacher who encouraged you to learn C, not everyone may be as fortunate. Therefore, mixing C in a C++ program could be confusing to someone who had never learned C.

In summary, just because you can do something doesn't mean you should, and just because you shouldn't do something doesn't mean you can't :)

share|improve this answer
    
I see. What about functionality, are there any particular cases when C syntax is better than C++ syntax? –  Bugster Feb 13 '12 at 20:59
3  
@ThePlan: Not really. That's why C++ was invented and grew popular. –  DeadMG Feb 13 '12 at 21:49
add comment

C++ is backward compatible with C by design, so usually C code will be compiled by C++ compiler just fine (usually because there are additional reserved words in C++ that are not in C, and could be used in C code breaking the compilation).

However, I see it as bad practice mixing code. If you use scanf - use printf, if you're using operator >> - use operator <<. Reason being that the overloaded C++ operators might encapsulate functionality that you're not aware of, and mismatching them will cause your program doing stuff you didn't want it to do.

There's no particular reason to prefer C syntax in C++ code, these are different languages, and when using C syntax in C++ code - you're still writing C++ code, just not using many of its powerful tools.

share|improve this answer
2  
The incompatibility between C and C++ is more than just keywords. The typing system changes, and there are features that exist in C (especially C99), that do not exist in C++. (Eg, variable-length arrays). –  Arafangion Feb 14 '12 at 7:04
add comment

The reason why C++ can compile C is only for "backward compatibility" (avoid to rewrite existing working code).

But C++ has a different philosophy respect to c. Mixing them up doesn't do a good service to both of them.

The way C and C++ manage i/o can rely on a different way to manage the i/o internal state. So -at least- use input and output consistently.

And in C++ programs respect C++ style (unless specifically required to do elsewhere)

share|improve this answer
add comment

If we put aside the coding style and esthetic issues, there are also various technical problems that you face when using C in C++ code:

  • What is C? C90, C99 or C11? There may be various compatibility issues depending on which C standard you are using. Boolean type, // comments, C99 features like VLAs, designated initializers etc.

  • C++ has stricter typing than C. In order to compile C code in C++, you must most likely add various typecasts to get the expected type. This means that you might have to rewrite perfectly fine, production-quality C code to get it working in C++.

  • The typecasts enfored by stricter typing are generally just a good thing, but in some cases they can introduce or hide away bugs. Take the infamous cast of the result from malloc() as an example. This should be typecasted in C++, but never in C. (1)

  • Mixing C and C++ functionality can lead to bugs and undefined behavior. For example, it will not work to allocate with malloc() and freeing with delete. (2)

  • Thread safety issues. The C standard library is not thread safe. The standard C++ library may or may not be thread safe, if it is, then adding C library function calls to your code will destroy that.

    As a sidenote for Windows programmers: the Visual C++ compiler had a leak bug for quite some time, when the Windows API CreateThread() function was used in the same program as the C library. (3, 4)

  • Calling convention might be an issue on some compilers, forcing one to use extern "C" to explicitly tell which functions that should be linked with "C calling convention".

  • Annoying details. Comma operator behaves differently. Trailing comma in struct/enum declarations is allowed in C99/C11 but not C++. The scope of various kinds of variables and functions are treated differently. Etc etc.

There are likely even more cases.


References:

  1. http://c-faq.com/malloc/cast.html
  2. http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.3
  3. http://www.flounder.com/badprogram.htm#CreateThread
  4. http://msdn.microsoft.com/en-us/library/windows/desktop/ms682453%28v=vs.85%29.aspx
share|improve this answer
add comment

I would say that learning C first is, IMHO, a good idea. This way people start understanding the hardware they write the software for.

Mixing these two languages is not necessary good idea though. Because you get the insane complexity of C++ coupled with raw bit twiddling common to C.

As you can see, in even such simple example as yours, there is a synchronization issues with different types of streams, and internal buffering. But also, the C&C++ approach is not any more flexible by any means. Switch to class x, and there are no operators to use streaming and stuff.

It's complicated...

I really think that good C++ programmer should know how bit's are flipped behind every construct, and what are the hidden behaviors.

But learning C++, at least more than 50% of it, takes 5+ years of professional coding, and you just can't manage that in the curriculum which is 6 months long with 20 or so hours of hands on experience.

If I would be using C++ constructs in C, I would not use streams, they are way to simple from birds eye view, and make people believe that software development is easy, but hide extra complexities without a lot of benefit in many situations.

RAII wrapper classes, templates, overloads, const correctness and pure abstract classes for common interfaces (don't use the f-ng Java way here PLEASE!) are good candidates though. Because they add safety, generality and ease of use which are very important for real life projects. Be sure to remember about things like virtual destruction, the explosive nature of default copy construction, runtime overhead, const correctness etc. here as well, though.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.