Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 598
Gustavo Puma Avatar asked Sep 28 '10 13:09

Gustavo Puma


People also ask

Are C macros bad practice?

"Macros are unsafe, have no type checking and should be avoided whenever possible. An alternative to macro is inline function for some use cases." He is right that a macro doesn't respect a namespace. That's just a caveat of using one.

Is using #define bad?

One major problem with #define is that it is outside of the language itself and therefore is not limited to a given scope. You will replace dItemName anywhere in the translation unit, in all namespaces, classes, functions, etc. Save this answer.

Is it bad to use new in C++?

Generally, new is not such bad practice, and it's not a bad idea. The answer you linked recommends removing the new() s to address a compile-time error: You can't pass a pointer to a function that doesn't expect one! If you did away with "raw pointer" in C++ you wouldn't have much left.

Is it good to use macros in C++?

So, macros not only make names shorter, and infact typedefs and ref alias can also be used to make names shorter, but macros can also avoid runtime overheads. Macros happen way before runtime. Macros have been avoiding run time over heads way before CPP features such as move and template.


2 Answers

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.

like image 124
Naveen Avatar answered Sep 27 '22 21:09

Naveen


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.

like image 27
Eli Bendersky Avatar answered Sep 27 '22 20:09

Eli Bendersky