How to determine the result of assigning multi-character char constant to a char variable?

后端 未结 5 482
陌清茗
陌清茗 2020-11-30 14:56

Why a char variable gets \'b\' from assignment of \'ab\', rather \'a\'?

char c = \'ab\';

printf(\"c: %c\\n\", c);

Prints:

         


        
5条回答
  •  醉话见心
    2020-11-30 15:34

    Later edit: my answer was complementary to the ones before that stated pretty clearly that this is implementation specific behavior. I was under the impression the OP wanted to know, with that in mind, why the compiler chose 'b' over 'a'. Sorry if my answer was confusing.

    Endianess. That's why you get 'b' instead of 'a'. Because of how that is represented in your machine's memory. And your machine is probably little endian.

    Try it on a sparc or on a mipsbe or on an arm and you might get 'a' instead of 'b'.

    In any case I hope you're not depending on this for actual production code.

提交回复
热议问题