1

In the C language, The answer of

char c='61'; 
printf ("%d", c);

is 49. The answer of

char c='61'; 
printf ("%c", c); 

is 1. The answer of

char c=61; 
printf ("%d", c);

is 61. The answer of

char c=61; 
printf ("%c", c);

is =. How is this happening exactly?

1
  • 2
    You are missing c=061; and c=0x61; to complete the set. Commented Aug 26, 2020 at 6:47

1 Answer 1

4

In the first two cases,

 char c='61';

have implementation-defined behaviour and not standard complaint. Quoting C11, chapter 6.4.5/P10

An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped character interpreted as an integer. The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined.[....]

It may not be a valid behaviour on your environment. Your compiler might have issued a warning there. Something like

warning: multi-character character constant [-Wmultichar]
     char c='61';
            ^~~~
warning: overflow in implicit constant conversion [-Woverflow]

In other two cases, read about most common character encoding, ASCII.

  • When you print the integer value using %d, it prints the value 61.

  • When you print the character representation of integer value 61 using %c, decimal value of 61 is for the ASCII character =. That gets printed.

Sign up to request clarification or add additional context in comments.

2 Comments

Small correction: First 2 cases are not invalid, but simply implementation defined (C17 draft §6.4.5 p10). It's still a good idea to avoid using them.
@user694733 Added the reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.