Introduction: I've been following K&R as my guide suggested. I came across the following code and I've been trying to figure out what's actually going on in the background.
Code:
// Program to count lines, words and characters in input
#include <stdio.h>
#define IN 1 // inside a word
#define OUT 0 // outside a word
int main()
{
int c, nl, nw, nc, state;
state = 0;
nl = nw = nc = 0;
while ((c = getchar()) != EOF)
{
++nc; // increment newchar count
if (c == '\n')
++nl; // increment newline count
if (c == ' ' || c == '\n' || c == '\t')
state = OUT;
else if (state == OUT)
{
state = IN;
++nw; // increment newword count
}
}
printf("%d %d %d\n", nl, nw, nc);
}
Question: I understand that after typing in the input, Ctrl+D(Linux/Mac Based OS) is needed to insert the EOF character which finally breaks the code out of the while loop to print the output, but what I'm unable to figure out is that what's happening in the background while I'm typing the input. Is the input being processed simultaneously and just waiting for Ctrl+D (EOF character) to print the output, or is all the input processed after Ctrl+D is processed.
In the former way, the processing power should the balanced but the latter way puts the entire load on the processor at once, and that's the reason I want to know how it's working.