Unexpected results when printing array and char to screen with cout

后端 未结 2 1764
灰色年华
灰色年华 2021-01-17 02:09

As a beginner of learning C++, I am trying to understand the difference between an array of type char and an array of type int. Here is my code:

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-17 02:39

    1.

    Because char arrays are treated differently to other arrays when you stream them to cout - the << operator is overloaded for const char*. This is for compatibility with C, so that null-terminated char arrays are treated as strings.

    See this question.

    2.

    This is due to integral promotion. When you call the binary + with a char (with value 'a') and an int (with value 1), the compiler promotes your char to either a signed int or an unsigned int. Which one is implementation specific - it depends on whether char is signed or unsigned by default, and which int can take the full range of char. So, the + operator is called with the values '97' and '1', and it returns the value '98'. To print that as a char, you need to first cast it:

    cout << "Print char array[0]+1: " << static_cast(array[0]+1) << endl;
    

    See this question.

提交回复
热议问题