putchar vs. printf. why difference in output?

This is a discussion on putchar vs. printf. why difference in output? within the C Programming forums, part of the General Programming Boards category; Hi everyone, This is my first post on this forum & I hope to hang around for a long time. ...

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    55

    putchar vs. printf. why difference in output?

    Hi everyone,

    This is my first post on this forum & I hope to hang around for a long time. I have started learning C as hobbyist. CPL by Kernighan & Ritchie is my main book and Google a sidekick .

    In one of the exercise in the book the value of EOF is asked to be printed. I used two methods:

    #include <stdio.h>

    main()
    {
    printf("The value of EOF is %d\n\n", EOF);


    }
    and

    #include <stdio.h>

    main()
    {
    putchar (EOF);

    }
    The output I get are different in both the cases. Why is that so?

  2. #2
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    putchar() writes the character c, cast to an unsigned char, to stream.
    EOF is usually -1. printf %d just print argument as int. Thus -1 printed.

  3. #3
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,657
    putchar actually puts the integer c to the stream: it just uses the first byte. I think the issue here is that whatever EOF is, it's non-printable as a character, so that is your difference in output. printf displays EOF's value, which is not the same obviously.
    Code:
    #include <assert.h>
    #include <ctype.h>
    #include <stdio.h>
    int main(void)
    {
            assert(isprint(EOF));
            return 0;
    }
    Assertion fails every time.

  4. #4
    Registered User
    Join Date
    Apr 2011
    Posts
    55
    Thanks indeed for help guys! That cleared my confusion.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Please help!
    By Cdre in forum C Programming
    Replies: 3
    Last Post: 02-12-2011, 09:14 AM
  2. C Code Please Help
    By Cdre in forum C Programming
    Replies: 3
    Last Post: 02-02-2011, 12:32 AM
  3. Replies: 3
    Last Post: 01-29-2011, 03:54 AM
  4. please help me finish my Hangman program (C)
    By eddybro in forum C Programming
    Replies: 1
    Last Post: 11-30-2010, 07:52 AM
  5. Azbia - a simple RPG game code
    By Unregistered in forum Game Programming
    Replies: 11
    Last Post: 05-03-2002, 06:59 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21