views:

38

answers:

1

I was fooling around with one of the sample programs in the K&R, and found that this

#include <stdio.h>

main()
{
    double nc;

    for (nc = 0; getchar() != EOF; ++nc)
        ;
    printf("%lf\n", nc );
    putchar(nc);
}

produces output that is 3.000000 (which I totally expected) then a new line with a heart on it (which I totally did not expect). Why would it output a new line with a heart on it? I assume it has something to do with me mixing data types.

+2  A: 

You're calling putchar() with a double as an argument. It's going to get implicitly typecast to int, and then that character will be output. You get the heart because for some reason your character set has a heart as character number 3. If you run it and type a bunch more characters before the EOF, you'll get a different character. On my machine, your program doesn't make a heart, but if I type more characters, I can get whatever I want on that next line. ASCII character 3 is ETX, end of text, so I don't know why you would get the heart in your case - are you using some weird locale or character set? What does this program output on your machine:

#include <stdio.h>

int main(int argc, char *argv[])
{
    putchar(3);
    putchar('\n');
    return 0;
}

Edit:

You're getting the heart because that's what's in your character set at position 3. From wikipedia:

In Code page 437, the original character set of the IBM PC, the value of 3 (hexadecimal 03) represents the heart symbol. This value is shared with the non-printing ETX control character, which overrides it in many contexts.

Carl Norum
That just makes a heart when I run it. :)
Laura
@Laura, yeah, that's expected. I edited my answer with some more information. Character 3 is a heart, and that's all there is to it.
Carl Norum
Thanks! Learned a little more today :)
Laura