void Functions to standard output stream

Just a small question!

Been challenged with creating a function that writes to the standard output stream (cout).

If my function is of type 'void' and as such does not specifically require the use of "cout << (function);" and just "(function);" I presume this still fulfills the criteria?

I'm presuming that by defining the function as void it is recognized that it contains no value and thus the need for explicitly writing "cout <<" is removed, even though it is still outputting to standard output stream?

Thanks
Technically, if you are required that a function write to the standard output stream, you are correct. If the function returns a value to be later written to the output stream, then the function itself didn't write to it, thus not completing your requirements.

Example: This function writes to an output stream (which can optionally be something other than cout)
1
2
3
4
5
std::ostream &writeString(std::string const &str, std::ostream &os = std::cout)
{
    os << str;
    return os;
}

Note that even though this function returns a value (something other than void) It still fulfills the requirements of writing to the output stream. Likewise could the function below, it just doesn't.

This function does not write to an output stream:
1
2
3
4
5
6
7
std::string makeUpperCase(std::string const &str)
{
    return std::toupper(str);
}

// Somewhere later in code
std::cout << makeUpperCase("some stuff here") << std::endl;
Last edited on
Cheers!
Topic archived. No new replies allowed.