Carl Walsh
Carl Walsh

Reputation: 6999

Can leaving out the "do" in a do-while loop still work?

I'm looking at some C code from my textbook, and it includes these lines

...
lastsec = get_seconds();
 sec0 = get_seconds(); while (sec0 == lastsec);
...

It looks rather like a do is missing at the end of that second line--but in any case code it should still compile.

I'm scratching my head as to how this loop wouldn't just sit at the while (sec0 == lastsec); until the end of time--assuming that get_seconds() didn't increment...

The book is Computer Architecture: A Quantitative Approach, Fifth Edition. Here's the code on page 134.

Upvotes: 0

Views: 132

Answers (4)

Patrick Schlüter
Patrick Schlüter

Reputation: 11871

It looks like a printing problem of the book. Look at the page, there are 2 other loops below the one you asked for, where the do { is missing. They even have the closing bracket of the block but no corresponding open bracket, and that twice. Even the comments talk about a loop /* repeat until collect 20 seconds*/

In my opinion, the printer swallowed the dos (probably that the printing language has that as a keyword or something like that).

From a logical point of view, it is a do while(); loop.

Upvotes: 1

P.P
P.P

Reputation: 121427

It's either infinite loop or condition fails the first time.

Possibly one of the variables in the condition is volatile and is asynchronously updated by some one else (thread, hardware etc) then it says: wait until condition becomes false.

Otherwise, it makes no sense to have such a loop.

Upvotes: 3

MOHAMED
MOHAMED

Reputation: 43578

in C there is 2 kind of while loop:

1)

do {.....} while(CONDITION);

2)

while(CONDITION) {........}

the while(CONDITION) {........} could be reduced to while(CONDITION) in some cases

for example if we want to copy char array we can do it in this way:

char *SRC="any string";
char DST[10]={0};
char *src = SRC, *dst =DST;
while(*dst++=*src++);

In the above example there is incrementation of src and dst pointer and the while will stop if the *src == null character.

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 71009

This is not a do-while loop, simply a while loop with empty body. In this case it seems this will either cause infinite loop or will never be executed.

Upvotes: 6

Related Questions