tags:

views:

59

answers:

3

Hi,

Can someone explain the following occurrence to me?

unsigned int i;
i = strlen("testData");
printf("%d\n", i);

Output:
8
5

Why is it printing the extra 5?

[Update:] After reading the comment, I stupidly realized where the 5 was coming from, sorry!

+1  A: 

strlen stands for string length. Now, let's see... "testData".

1 - 't' 2 - 'e' 3 - 's' 4 - 't' 5 - 'D' 6 - 'a' 7 - 't' 8 - 'a'.

we counted 8.
now i is 8.

So, printf("%d\n", i);
prints 8.

And then later you have some code in your program which prints 5. Can't tell you why because I can't see the code

Armen Tsirunyan
A: 

One possible explanation is that you have undefined behaviour because you are using a format specification for a signed integer (%d) but passing an unsigned int parameter. The correct printf call would be:

printf("%u\n", i);

Although unlikely, one possible explanation is that the undefined behaviour on your implementation results in the extra 5 being printed.

Charles Bailey
Is it really undefined behavior? Because the standard says int and unsigned int have both the same bit representation... Just curios, is it provable from the standard that this is UB?
Armen Tsirunyan
@Armen Tsirunyan: You have to refer to the C standard as that is where the `fprintf`/`printf` function interface is defined. ISO/IEC 9899:1999 7.19.6.1 says (paraphrased) for conversion specifiers `d`, `i`: "The `int` argument is ... " and later "If any argument is not the correct type for the corresponding conversion specification, the behaviour is undefined". Although I don't have C90 to hand, I don't believe this aspect has changed since then.
Charles Bailey
A: 

This code snippet should just print 8.There is something else beyond this code section that prints 5