#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    2
    Rep Power
    0

    Char printf in c


    I am new in C and doing self study. Someone please explain me the follo:
    char c='77';
    printf("%c\n...%d\n",c,c);
    Ignoring compiler Warnings I can understand %c prints 7 %d prints decimal value, but when I type"
    char c='\77';
    printf("%c\n...%d\n",c,c);
    Quest 1: Why %c prints ? and %d its decimal value. What is significance of \ ?
    Quest 2: If I use printf(2+"%c\n...%d\n",c,c); Why %c is not printed on screen but %d is printed ?
    Quest 3: If I use char c='\177'; Why %c is a del symbol and %d is its decimal value?
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,145
    Rep Power
    2222
    I don't normally use that character notation, but much rather prefer to use hex notation.

    Your problem is that you're using octal. '\77' is not an ASCII code of 77-decimal, but rather 77-octal, which is 63-decimal and '\x3f' (which is the hex notation that I prefer since it is much more explicit, plus hex is so much easier to read than octal is). All of which is the character '?'.

    Similarly, 177-octal is 0x7f, which is del.

    printf(2+"%c\n...%d\n",c,c); is weird; I've never seen such a thing done professionally in my 24 years experience. I think that it says to ignore the first two characters of the format string, so "%c" is gone and there's only the "%d" which uses the second argument (the format string itself is the first argument), leaving the third argument unused; change the second and third arguments to be different from each other in order to see which is being used with the "%d".

    And please never use '77'. And never ignore warnings; they are much more important than error messages.

    Comments on this post

    • imvijit agrees
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    2
    Rep Power
    0

    Thanks and one clarifiation reqd


    Thank you. Very much grateful for your reply. I never knew \77 would imply octal. Also didn't know warnings are important.
    Will pay proper attention to them:

    One clarification I require is how octals are printed on screen
    For eg:\377 implies 255 decimal
    But why does %o print 37777777777 in
    char c='\377';
    printf("%d\n...%o\n",c,c)

    But if I use unsigned char, %o prints 377 correctly?

    Have you seen same thing on Hex before? I am starting to tinker around with hex/ Would be grateful if you could give some ideas.

IMN logo majestic logo threadwatch logo seochat tools logo