0

I'm trying around wit times. I createt the following (useless) code:

char cChar0[30];
char cChar1[30];
char cChar2[30];
char cChar3[30];
char cChar4[30];

clock_t t1;
clock_t t2;
clock_t t3;

uint16_t t4;
uint32_t t5;

uint16_t i;
uint16_t uInitDone;

void dateTime (void){

    if(!uInitDone){
        uInitDone = 1;

        t1 = clock();
        for (i = 0; i < 1000; i++){
            sprintf(cChar0,"do something...");
        }
        t2 = clock();
        t3 = t2 - t1;
        t4 = (uint16_t)t2 - (uint16_t)t1;
        t5 = (uint32_t)t2 - (uint32_t)t1;

        sprintf(cChar1, "t1: %u; t2: %u;",t1,t2);
        sprintf(cChar2, "t1: %u; t2: %u;",(uint16_t)t1,(uint16_t)t2);
        sprintf(cChar3, "t1: %u; t:2 %u;",(uint32_t)t1,(uint32_t)t2); 
        sprintf(cChar4, "t3: %u; t4: %u; t5: %u;",t3,t4,t5);  
    }
}

int main(void) {
    while(1)
        dateTime();

    return 0;
}

I was suprised about the result:

cChar0 = "do something..."
cChar1 = "t1: 0;t2: 0;..."
cChar2 = "t1: 0;t2: 10498;..."
cChar3 = "t1: 0;t2: 0;..."
cChar4 = "t3: 1;t4: 10498; t5: 10498;..."

I checked in time.h and found the declaration:

typedef long time_t;

Can anyone explain to me why t2 in cChar1 and cChar3 = 0? Why is t3 in cChar4 = 1 though it seems to be the difference of 0 and 0 (cChar1)? Why is t5 in cChar4 = 10498 though it seems also to be the difference of 0 and 0 (cChar3)?

nobody
  • 23
  • 3
  • `typedef long time_t` basically means that `time_t` is the same thing as a `long`. That's what `typedef`s do in a nutshell – Alex Jul 25 '16 at 06:14
  • And why is t2 in cChar1 = cChar3 = 0 then? It's also the return value of clock(), which means of type long. – nobody Jul 25 '16 at 07:11

1 Answers1

1

When you do not know the exact type of a number, you must convert it explicitly to a fixed type before calling sprintf() with an appropriate format.

The bug in your code is you use format %u, which is inappropriate for type long.

Fix the sprintf() lines this way:

    sprintf(cChar1, "t1: %lu; t2: %lu;", (unsigned long)t1, (unsigned long)t2);
    sprintf(cChar2, "t1: %u; t2: %u;", (unsigned int)t1, (unsigned int)t2);
    sprintf(cChar3, "t1: %hu; t2: %hu;", (unsigned short)t1, (unsigned short)t2); 
    sprintf(cChar4, "t3: %lu; t4: %lu; t5: %lu;",
        (unsigned long)t3, (unsigned long)t4, (unsigned long)t5);  

The output should be more consistent now.

chqrlie
  • 131,814
  • 10
  • 121
  • 189