Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
March 5th, 2013, 11:21 AM
 imvijit
Registered User

Join Date: Mar 2013
Posts: 2
Time spent in forums: 22 m 52 sec
Reputation 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
March 5th, 2013, 12:08 PM
 dwise1_aol
Contributing User

Join Date: Jan 2003
Location: USA
Posts: 6,883
Time spent in forums: 3 Months 1 Day 15 h 47 m 56 sec
Reputation Power: 2199
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.
imvijit agrees!

#3
March 5th, 2013, 02:59 PM
 imvijit
Registered User

Join Date: Mar 2013
Posts: 2
Time spent in forums: 22 m 52 sec
Reputation 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.

 Viewing: Dev Shed Forums > Programming Languages > C Programming > Char printf in c