-2

I have this code

#include <stdio.h>

int main()
{
    
        char c='31';
        printf("%d\n",c);

}

The above one prints wrong 49. It should have printed 31. Can this be done in C. I believe 31 is not number 31 that means '31' is not represented as binary 00011111=31 so is this true so it can't be done or make sense doing it in C

user786
  • 3,902
  • 4
  • 40
  • 72
  • 2
    `'31'` is not a char and obviously can't be stored in a single char. Enable all warnings and read it, you'll see what's wrong with your problem. For the numeric value use `char c = 31`. See [Multicharacter literal in C and C++](https://stackoverflow.com/q/3960954/995714) – phuclv Mar 11 '22 at 03:49
  • It's not clear what you are trying to do. Is `char c=31;` what you actually want? – kaylum Mar 11 '22 at 03:50
  • @kaylum I like to know are '31' and 31 same or different – user786 Mar 11 '22 at 03:53
  • 2
    Note that `'3'` also is not a `char` in C, but an `int`. The unexpected result is not so much one of type, but of value. – chux - Reinstate Monica Mar 11 '22 at 04:15

3 Answers3

2

Code did not assign 31

To assign 31, use:

    //char c='31';
    char c = 31;  // drop the ''

Multi-byte character constant

'31' is a multi-byte character constant with an implementation specific value. In OP's case, it is an int with likely the ASCII values 51 for '3' and 49 for '1' joined together in big-endian fashion as a base-256 number or 51*256 + 49.

Since this value is outside the char range, it is converted as part of the assignment - likely by only retaining the least significant 8-bits - to 49. This is what OP saw.

Save time

Enable all compiler warnings. Most of the time, coding a multi-byte character constant is a coding error. Multi-byte character constants are rarely used and often discouraged by various style standards.
There are an old feature of C not often used today due to the implementations details of int size, endian and character encoding make for difficulties in portable code.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

If you want to assign 31 to char, just assign it as follows

char c = 31;

31 means int which will easily fit into 8bits .

balu
  • 1,023
  • 12
  • 18
0

Char type will only take one letter, number, or symbol. The char c will equal '3', then '1' will override it. The int value of of '1' is 49.

int -- %d char -- %c string -- %s

try

#include <stdio.h>

int main()
{
    char c[3] = {'3','1','\0'};
    printf("%s\n",c);
}
  • 1
    `The char c will equal '3', then '1' will override it` this is completely wrong. The value is implementation defined – phuclv Mar 11 '22 at 04:17