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
CodePudding user response:
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.
CodePudding user response:
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 .
CodePudding user response:
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);
}