I've started using C++ recently and I've felt a strong urge to
#define print(msg) std::cout << msg << std::endl
Will this perform correctly in all situations? This is the only formulation I'm aware of that will work when there's a << in msg (e.g. "foo" << myInt). Neither
#define print(msg) std::cout << (msg) << std::endl // note: parens
nor the suggested answer
template<typename T>
void print(T const& msg) {
std::cout << msg << std::endl;
}
work in this case. I also don't care about the efficiency of flushing the output with endl vs just using \n.
Since you mention you have just started using C++ recently, I would like to show you a better alternative that the language offers:
template<typename T>
void print(T const& msg)
{
std::cout << msg << std::endl;
}
It takes a single msg argument of any type, and it streams it out via std::cout.
As mentioned in the comments, std::endl does not only insert a new line but also flushes the stream. This is akin to printf flushing on \n. If you just want a new line, and you probably do, better do that explicitly:
std::cout << msg << '\n';
This is pretty subjective, but you write code once and read it many times. Other maintainers of the code will want to understand what you've written, so just write std::cout << msg << std::endl when that's what you mean. Don't try to make C++ look like another language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With