C++ Pointers and the Flush function

  • Context: C/C++ 
  • Thread starter Thread starter ineedhelpnow
  • Start date Start date
  • Tags Tags
    C++ Function Pointers
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 2K views
ineedhelpnow
Messages
649
Reaction score
0
I need some help understanding some things.
One, I understand WHAT pointers do but how are they useful and how/when are they necessary?
Two, what is the purpose of the flush function? This is the definition that I've been given: "The << flush forces count to flush any characters in its buffer to the screen before doing each task, otherwise the characters may be held in the buffer until after a later task completes." I'm not able to really understand it. Can someone clarify?
 
Physics news on Phys.org
For your first question, read up on the concept of indirection, that is, addressing an object by some piece of information other than the object itself. For instance, if I want to visit your house, I am not going to contract workers and engineers to build a perfect replica of your house next to mine, check it out, and then ask them to destroy it when I'm done. You just give me your address instead and I can go there myself. Here your home address is a kind of "pointer". Similarly, if you have a function that needs to access a large buffer in memory, you don't make a copy of the buffer and give it to the function, that would be a waste, you just tell the function where to find the buffer in memory (= a pointer to the buffer).

There are other use cases for pointers, which you will eventually encounter if you keep programming. Needless to say, they are important.

For your second question, each time you actually write some text to the console there is some significant amount of input/output overhead. So the text you send with count or whatever is not sent to the console character by character, instead it is stored into a fast memory buffer until a full line is stored (by default; for other types of files it could instead wait for a certain number of characters) and that line is then sent to the console all in one shot. In this context "flush" simply means to directly send whatever is in the buffer directly to the console without waiting for it to be ready to be sent.