Tyilo
Tyilo

Reputation: 30122

Comparing old variable value to new value in a while-statement?

Why doesn't this code print "New time", more than once? And is it possible to fix, without calling clock() outside the loop?

#include <stdio.h>
#include <time.h>
int main(char argv[], int argc)
{
    double lastTime = 0;
    while(1)
    {
        printf("New time:\n");
        while(lastTime == (lastTime = (double)clock() / (double)CLOCKS_PER_SEC))
        {
            printf("%f\n", lastTime);
        }
    }
    return 0;
}

Upvotes: 0

Views: 1245

Answers (2)

Mario
Mario

Reputation: 36517

This line won't work as you might expect (I've added the closing brackets cause they were missing above):

while(lastTime == (lastTime = (double)clock() / (double)CLOCKS_PER_S))

Due to the brackets the right side of the comparison (the assignment) is evaluated first, essentially resulting in this:

while(lastTime == lastTime)

Which essentially leads to while(0 == 0), which is obviously while(true).

You'll need at least a second variable to hold the previous value. Then just add an extra case for when lastTime == 0 (i.e. the first time the loop is run).


Also, as mentioned in a comment above, you shouldn't compare the value as it's not that easy for two double values to be exactly the same (esp. when calculated).

If you'd like to do some action every x milliseconds (or any other time), you should use a counter to add up the time passed:

for(clock_t timeSkipped = 0, lastTick = clock() ; ; timeSkipped += clock() - lastTick, lastTick = clock()) {
    while(timeSkipped > 0.5 * CLOCKS_PER_S) { // example: this will run the content of this loop at a fixed time step of once every half second
        timeSkipped -= 0.5 * CLOCKS_PER_S;
        printf("Tick!");
    }

}

Upvotes: 0

blueshift
blueshift

Reputation: 6882

Your code seems to have been cut off. But your problem is with this logic:

while (lastTime == (lastTime = something))

The test will always be true; you assign some value to lastTime, then compare it with itself.

Upvotes: 4

Related Questions