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;
}
This line won’t work as you might expect (I’ve added the closing brackets cause they were missing above):
Due to the brackets the right side of the comparison (the assignment) is evaluated first, essentially resulting in this:
Which essentially leads to
while(0 == 0), which is obviouslywhile(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:
}