March 5th, 2013, 10:21 AM
Char printf in c
I am new in C and doing self study. Someone please explain me the follo:
Ignoring compiler Warnings I can understand %c prints 7 %d prints decimal value, but when I type"
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?
March 5th, 2013, 11:08 AM
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
March 5th, 2013, 01:59 PM
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
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.