Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are 4 characters allowed in a char variable? [duplicate]

Tags:

c

I have the following code in my program:

char ch='abcd';
printf("%c",ch);

The output is d.

I fail to understand why is a char variable allowed to take in 4 characters in its declaration without giving a compile time error.

Note: More than 4 characters is giving an error.

like image 271
user3152736 Avatar asked Jan 02 '14 07:01

user3152736


2 Answers

'abcd' is called a multicharacter constant, and will has an implementation-defined value, here your compiler gives you 'd'.

If you use gcc and compile your code with -Wmultichar or -Wall, gcc will warn you about this.

like image 188
Lee Duhem Avatar answered Sep 17 '22 17:09

Lee Duhem


I fail to understand why is a char variable allowed to take in 4 characters in its declaration without giving a compile time error.

It's not packing 4 characters into one char. The multi-character const 'abcd' is of type int and then the compiler does constant conversion to convert it to char (which overflows in this case).

like image 28
tristan Avatar answered Sep 17 '22 17:09

tristan