0

I'm learning c++ char type variable and what i learn is that sizeof(char) = 1 which means it can only hold 1 ASCII character. I'm using Visual Studio 2019 and Here's the strange behavior i've found:

char x = 'abcd';
std::cout << x;   //it prints 'd', the last letter.
char y = 'dcba';
std::cout << y;   //it prints 'a', the last letter.

surprisingly, it still compile and give the output as commented above. What is Visual Studio doing here? what's the logic behind outputting the last character?

However, when i do:

char x = 'abcde'; 

Visual Studio has warn me "too many characters in character constant", and cannot compile at all! Again, what's the logic here? If char cannot take more than 1 character, why does it still accept a input of length 1 to 4, but not anything more than 4?

VS warning message

Jeremy
  • 379
  • 2
  • 11
  • There is a difference between the `char` on the left of the assignment, and the "multicharacter literal" on the right, which could be assigned to a `wchar_t` for example. It's a bit like assigning a `double` into a `float`; the value will be truncated. – BoBTFish Oct 04 '19 at 06:31
  • @hobbs, I've seen that question, not exactly sir – Jeremy Oct 04 '19 at 06:31
  • @Inian That is not correct, see https://en.cppreference.com/w/cpp/language/character_literal – VLL Oct 04 '19 at 06:41
  • As explained in the duplicate a multi-character literal is an `int`. As an `int` in visual studio is 4 bytes if you enter more than 4 characters visual studio issues a warning. – Alan Birtles Oct 04 '19 at 06:46
  • @AlanBirtles Thanks, so the first question on why it truncated and output the last letter, is also something by default? – Jeremy Oct 04 '19 at 06:50
  • @Ville-Valtteri: Yes I pasted the wrong text, a few lines above (from C++ PL 4th edition) I see "It is possible to enclose more than one character in a character literal, for example,`'ab'`. Such uses are archaic, implementation-dependent, and best avoided. The type of such a multicharacter literal is `int`. – Inian Oct 04 '19 at 06:50
  • you're assigning an `int` to a `char`, that will truncate to the least significant byte in the `int` – Alan Birtles Oct 04 '19 at 06:51

0 Answers0