The code I wrote for a digital clock always falls behind the clock in my windows 7 taskbar after being run for like 2-3 mins. Why?
Here's the code:

#include <stdio.h>
#include <time.h>
#include <windows.h>

int main() 
{   
    int h,m,s;
    time_t epoch_time;
    struct tm *tm_p;
    epoch_time = time( NULL );
    tm_p = localtime( &epoch_time );

h=tm_p->tm_hour%12;
m=tm_p->tm_min;
s=tm_p->tm_sec;
while(1)
{

if(s>59)
{
m=m+1;
s=0;
}
if(m>59)
{
h=h+1;
m=0;
}
if(h>11)
{
h=0;
m=0;
s=0;
}
Sleep(1000);
s++; // trying something I learned (s=s+1)
system ("cls");
printf(" %d:%d:%d",h,m,s);
}
}

I didn't look over your code because its not enclosed within code tags.

However have you considered that your program does not run continuously since its scheduled ran and rescheduled again.

I didn't look over your code because its not enclosed within code tags.

However have you considered that your program does not run continuously since its scheduled ran and rescheduled again.

:sad:

#include <stdio.h>
#include <time.h>
#include <windows.h>

int main() 
{   int h,m,s;
    time_t epoch_time;
    struct tm *tm_p;
    epoch_time = time( NULL );
    tm_p = localtime( &epoch_time );

h=tm_p->tm_hour%12;
m=tm_p->tm_min;
s=tm_p->tm_sec;
while(1)
{

if(s>59)
{
m=m+1;
s=0;
}
if(m>59)
{
h=h+1;
m=0;
}
if(h>12)
{
h=0;
m=0;
s=0;
}
Sleep(1000);
s++; // trying something I learned
system ("cls");
printf("%d:%d:%d",h,m,s);
}
}

I don't understand isn't that the only way to do this?

Clocks aren't as easy as they look. For instance, Sleep(N) gives you AT LEAST N periods of time - but note the "at least" part of that. ;)

Because other programs and lots of Windows services (programs without a terminal window for output), are running, many times you'll get more sleep time than you bargained for.

Also, you have left zero time for your program to actually run - agreed it won't need much, but surely it will need some time.

So, what to do? One way is to subtract the amount of time you get back from the system, from either a minute, or the amount that you asked for. Then adjust how much time you ask for on the next loop, to account for it (basically, subtract it).

You ask for 60 seconds, and you got 60.5 seconds. So you ask for 59.5 seconds, on your next loop. You asked for 59.5 seconds, but you got 59.7 seconds. You ask for 59.8 seconds on your next loop (because it was .2 seconds behind what you asked for last time). And continue with that type of "carry over" logic.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.