Re: Why is my C++ timer stuck in infinite loop?
From: Ulrich Eckhardt (doomster_at_knuut.de)
Date: Tue, 29 Mar 2005 10:37:13 +0200
> time_t timerStart = ((time (0)) +5); // Add 5 sec to current time
> time_t timerFinish = time (0); // Get current time
> for ( ; timerStart >= timerFinish ; ) // Compare the two values loop
> cout << ".";
> time_t timerFinish = time (0);
Look closely: inside the loop's body, you create a local variable called
timerFinish, the same name as (but a distinct object from) the one you
create in the function's body.
BTW, when using for-loops the scheme is
for( init; condition; next)
so for your case that should be
for( time_t timerFinish = time(0);
or even better
That way, you avoid the hassle with a temporary (exactly the one where you
made a mistake).
However, since there is not much left to init or to do on every iteration,
you could replace it with a while() loop:
Now, there is only one nit left: 'timerStart' is not the starttime or
anything like that, it is the endtime! IOW, your variable is misnamed.
A last thing that might spoil your fun is that std::cout works line-based.
That means it first collects a line before it finally prints it. For
writing the dots, you should tell it to print all stuff after each dot:
std::cout << '.' << std::flush;