When I declare char ch = 'ab' , ch contains only 'b', why it is not storing 'a'?
#include <stdio.h>
int main()
{
char ch = 'ab';
printf("%c",ch);
return 0;
}
What is the actual process involved here?
When I declare char ch = 'ab' , ch contains only 'b', why it is not storing 'a'?
#include <stdio.h>
int main()
{
char ch = 'ab';
printf("%c",ch);
return 0;
}
What is the actual process involved here?
When using the single quote marks ' to contain the ab string, you have created what is known as a multi-character constant. The behaviour of your program is implementation-defined, meaning that if I have a different compiler or OS, I might see the value a, even though you see the value b.
This is not a good practice and the compiler should issue a warning.
If you do not see the warning, try compiling with warnings enabled by using the flags -Wall and -Wextra if using gcc or clang.
You can read more about this here in another answer.
A character literal, for example 'A', has the type int with the value of 'A', most likely 0x41 (ASCII-Value for A).
When you have more than 1 byte in a character literal, for example 'ab', the result is implementation-defined. Note that the same applies to an Unicode codepoint when stored in UTF-8 with more than 1 byte, means every codepoint outside of ASCII, for example '✓' is a multi-character constant.
On my system it is still of type int and every byte is stored in 8 bit of this int, this is probably the case on your system as well. 'ab' results in the value 0x6162, 0x61 is the value for 'a' and 0x62 the value for 'b'. You assign the value 0x6162 to a 8-bit char, you create UB when char is signed, so do not do that. In your case it stores the lower 8 bit of the value in the char, as it also would do when unsigned char is used. (Do not relay on this behavior in case of signed char or char on systems where char is signed).
You can test the value of 'ab':
#include <stdio.h>
int main(void)
{
unsigned ch = 'ab';
printf("0x%04X\n",ch);
return 0;
}
This outputs 0x6162 on my system.