What's the behaviour of “” + number and why c++ compile it?

后端 未结 2 1303
温柔的废话
温柔的废话 2021-01-25 02:48

In the code below i successfully compile it but i can\'t understand why for certain values of number the program crash and for other values it\'s not. Could someone explain the

2条回答
  •  悲&欢浪女
    2021-01-25 03:41

    Pointer arithmetic is the culprit.

    A const char* is accepted by operator<<, but will not point to a valid memory address in your example.

    If you switch on -Wall, you will see a compiler warning about that:

    main.cpp: In function 'int main()':
    main.cpp:6:59: warning: array subscript 255 is outside array bounds of 'const char [1]' [-Warray-bounds]
        6 |     std::cout<< "Value 1 : " << std::flush << ("" + number) << std::flush << std::endl;
          |                                                           ^
    main.cpp:8:59: warning: array subscript 15155 is outside array bounds of 'const char [1]' [-Warray-bounds]
        8 |     std::cout<< "Value 2 : " << std::flush << ("" + number) << std::flush << std::endl;
          |                                                           ^
    Value 1 :  q
    

    Live Demo

提交回复
热议问题