The trouble with any loops, be they while(TRUE)
or while(condition)
, is their tendency to have a sneak infinite loop condition - like this one.
OP's code depends on 2 results of scanf("%d",...
,: 1
and not 1
.
If user enters "123"
, all is good. scanf()
returns 1
, loop exits, we all leave work and have a pint.
If user enters "abc"
, scanf()
returns 0
, code does a fflush(stdin)
to empty the stdin
. (This is really UB, but let us pretend it works.) Code loops, prompts again, our drinks get warm, but hopefully we will eventually enter digits.
But let us imagine the user closed stdin
- maybe code had re-directed input and scanf()
eventually returns EOF
. Code loops, but fflush(stdin)
does not re-open stdin
, and scanf()
again returns EOF
- and again and again - true infinite loop - code will not pause for input and just says ""Invalid input. Try again." which translates into "dumb guy, dumb guy, dumb guy ...". Looks like the crew will start their brews without us.
Moral of the story: loop when code is working as intended (User entered good data). Watch out for loops when functions loops on the unexpected.