A buffer flush is the transfer of computer data from a temporary storage area to the computer’s permanent memory. For instance if we make any changes in a file, the changes we see on one computer screen are stored temporarily in a buffer.
Usually a temporary file come into existence when we open any word document, and automatically destroyed when we close our main file. Thus when we save our work, the changes that we’ve made to our document since the last time we saved it are flushed from the buffer to permanent storage on the hard disk.
In C++, we can explicitly flushed to forced the buffer to be written. Generally std::endl function works the same by inserting new-line character and flushes the stream. stdout/cout is line-buffered that is the output doesn’t get sent to the OS until you write a newline or explicitly flush the buffer. For instance,
But there is certain disadvantage something like,
The above program will output 1 2 3 4 5 at once.
Therefore in such cases additional “flush” function is used to ensure that the output gets displayed according to our requirement. For instance,
The above program will program will print the numbers(1 2 3 4 5) one by one rather than once. The reason is flush function flushed the output to the file/terminal instantly.
- You can’t run the program on online compiler to see the difference, since they give output only when it terminates. Hence you need to run all above programs in offline complier like gcc or clang.
- Reading cin flushes cout so we don’t need an explicit flush to do this.
Related Article :
Use of fflush(stdin) in C
This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Buffer Overflow Attack with Example
- Clearing The Input Buffer In C/C++
- Difference between cout and puts() in C++ with Examples
- Difference between forward list and list in C++
- Short-Circuiting in C++ and Linux
- Different types of range-based for loop iterators in C++
- Learn C++ Programming Step by Step - A 20 Day Curriculum!
- Why do we need reference variables if we have pointers
- Similarities and Difference between Java and C++
- Macros and its types in C/C++
- Reversed Range-based for loop in C++ with Examples
- How to find index of a given element in a Vector in C++
- Introduction to Complex Objects and Composition
- NULL undeclared error in C/C++ and how to resolve it
Improved By : PaneerParatha69