Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"--" operator in while ( ) loop

Tags:

c

I am reading K&R book, on page 63 there is a line

while (--lim > 0 && (c=getchar()) != EOF && c != '\n')

where lim is int equal to 1000

My question, why is lim is not decreasing after consequential runs of while loop ? As I see it, --lim is equivalent to "lim = lim - 1"

===================================================================

Thanks for all the answers !

like image 647
newprint Avatar asked Jun 08 '26 22:06

newprint


1 Answers

--lim means "take one from the value of lim and use the result".

The alternative lim-- would be "use the value of lim and then take one away".

So if lim starts at 1000 the first time the loop executes it will have the value 999 before it is checked to see if it's greater than 0. If it were lim-- then the value that would be checked would be 1000, but it would still have the value of 999 at the end of the iteration through the loop. This is important at the start and end of the loop.

The MSDN as a page on this Prefix Increment and Decrement Operators

When the operator appears before its operand, the operand is incremented or decremented and its new value is the result of the expression.

like image 120
ChrisF Avatar answered Jun 10 '26 19:06

ChrisF