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

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

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

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

    It depends on which features. Using define macros in C++ is strongly frowned upon, and for a good reason. You can almost always replace a use of a define macro with something more maintainable and safe in C++ (templates, inline functions, etc.)

    Streams, on the other hand, are rightly judged by some people to be very slow and I've seen a lot of valid and high-quality C++ code using C's FILE* with its host of functions instead.

    And another thing: with all due respect to the plethora of stream formatting possibilities, for stuff like simple debug printouts, IMHO you just can't beat the succinctness of printf and its format string.

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

    You should definitely use printf in place of cout. The latter does let you make most or all of the formatting controls printf allows, but it does so in a stateful way. I.e. the current formatting mode is stored as part of the (global) object. This means bad code can leave cout in a state where subsequent output gets misformatted unless you reset all the formatting every time you use it. It also wreaks havoc with threaded usage.

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

    For allocations, I would avoid using malloc/free altogether and just stick to new/delete.

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

    Coming from a slightly different angle, I'd say it's bad to use scanf in C, never mind C++. User input is just far to variable to be parsed reliably with scanf.

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