Little question about functions.

Hello people. I would like to know if it is bad that a function prints something on screen and returns some value. I mean something like this:

1
2
3
4
5
6
7
8
9

int function (*Parameters*)
{
int i=23;

cout<<"Hello CPlusPlus.com \n";

return i;
}


thank you for your help!
There's nothing inherently dangerous about having a function output something. It's certainly not good that you don't flush the output stream, as you then can't know when the output will actually appear.
Last edited on
It's certainly not good that you don't flush the output stream, as you then can't know when the output will actually appear.


Thanks for the answer, but can you explain the part above please.
When you pass something to cout as above, it may or may not actually appear on screen straight away. It may wait a while. You can guarantee it will appear immediately by flushing the stream.

http://www.cplusplus.com/reference/iostream/ostream/flush/

There are other way to flush the stream as well. For example, cout << endl;
Don't get it, you mean I should use
cout << endl;
instead of
\n
?
No. I don't mean that at all. I'm not talking about that at all.

I'm saying that when you send something to cout, you are not actually sending it to screen. You are sending it to a buffer somewhere, and it will appear on screen when something else decides. Might be straight away. Might be in the future. If you want it to come out on screen now, you must do something called flushing.

Here is one way you can flush:

cout << endl;

Here is another way you can flush:
cout.flush();

This has nothing at all to do with your choice of endl and \n

Last edited on
Topic archived. No new replies allowed.