Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What do you mean by buffer in C language?
A buffer in C is a temporary storage area that holds data before it is processed. All input/output (I/O) devices contain I/O buffers to manage data flow efficiently.
When you provide more input values than required, the extra values remain stored in the input buffer. This buffered data automatically gets consumed by the next input operation if one exists. Understanding and managing buffers is crucial for preventing unexpected behavior in C programs.
Syntax
int fflush(FILE *stream); void flushall(void); /* Non-standard, compiler-specific */
Example: Buffer Behavior Demonstration
The following program demonstrates how input buffer works when extra values are provided −
#include <stdio.h>
int main() {
int a, b;
printf("Enter a value: ");
scanf("%d", &a);
printf("Enter b value: ");
scanf("%d", &b);
printf("a + b = %d<br>", a + b);
return 0;
}
When you enter multiple values for the first input (like "1 2 3"), the extra values remain in the buffer −
Enter a value: 1 2 3 Enter b value: a + b = 3
Notice that the second scanf() automatically takes "2" from the buffer without waiting for user input.
Example: Clearing Input Buffer
To prevent unwanted buffer data from affecting subsequent input operations, we can clear the buffer −
#include <stdio.h>
int main() {
int a, b;
int c;
printf("Enter a value: ");
scanf("%d", &a);
/* Clear input buffer */
while ((c = getchar()) != '<br>' && c != EOF);
printf("Enter b value: ");
scanf("%d", &b);
printf("a + b = %d<br>", a + b);
return 0;
}
Enter a value: 1 2 3 Enter b value: 5 a + b = 6
Buffer Management Functions
- fflush(stdin) − Clears the input buffer (behavior is undefined in standard C)
- fflush(stdout) − Forces output buffer to be written immediately
- flushall() − Non-standard function that clears all buffers (compiler-specific)
Key Points
- Input buffers store extra data until the next input operation consumes it
- Use manual buffer clearing techniques like
getchar()loops for portable code - Avoid
fflush(stdin)as its behavior is undefined in standard C
Conclusion
Buffers in C temporarily store I/O data, and extra input values remain buffered for subsequent operations. Proper buffer management prevents unexpected program behavior and ensures predictable input handling.
