Is it bad practice to use C features in C++?

前端 未结 10 1967
悲哀的现实
悲哀的现实 2021-02-19 00:16

For example printf instead of cout, scanf instead of cin, using #define macros, etc?

相关标签:
10条回答
  • 2021-02-19 00:38

    What can be used or not only depends on the compiler that will be used. Since you are programming in c++, in my opinion, to maximize compatibility it is better to use what c++ provides instead of c functions unless you do not have any other choices.

    0 讨论(0)
  • 2021-02-19 00:38

    I'd just post a comment to another reply, but since I can't... C's printf() is better than C++'s iostream because of internationalization. Want to translate a string and put the embedded number in a different place? Can't do it with an ostream. printf()'s format specification is a whole little language unto itself, interpreted at runtime.

    0 讨论(0)
  • 2021-02-19 00:38

    I wouldn't say bad as it will depend on the personal choice. My policy is when there is a type-safe alternatives is available in C++, use them as it will reduce the errors in the code.

    0 讨论(0)
  • 2021-02-19 00:42

    There are better solutions for most cases, but not all.

    For example, people quite often use memcpy. I would almost never do that (except in really low-level code). I always use std::copy, even on pointers.

    The same counts for the input/output routines. But it’s true that sometimes, C-style printf is substantially easier to use than cout (especially in logging). If Boost.Format isn’t an option then sure, use C.

    #define is a different beast entirely. It’s not really a C-only feature, and there are many legitimate uses for it in C++. (But many more that aren’t.)

    Of course you’d never use it to define constants (that’s what const is for), nor to declare inline functions (use inline and templates!).

    On the other hand, it is often useful to generate debugging assertions and generally as a code generation tool. For example, I’m unit-testing class templates and without extensive use of macros, this would be a real pain in the *ss. Using macros here isn’t nice but it saves literally thousands of lines of code.

    0 讨论(0)
  • 2021-02-19 00:44

    I would say the only ones that are truly harmful to mix are the pairings between malloc/free and new/delete.

    Otherwise it's really a style thing...and while the C is compatible with the C++, why would you want to mix the two languages when C++ has everything you need without falling back?

    0 讨论(0)
  • 2021-02-19 00:49

    Not really, printf() is quite faster than cout, and the c++ iostream library is quite large. It depends on the user preference or the program itself (is it needed? etc). Also, scanf() is not suitable to use anymore, I prefer fgets().

    0 讨论(0)
提交回复
热议问题