C++ crashes in a 'for' loop with a negative expression

前端 未结 8 969
遇见更好的自我
遇见更好的自我 2020-12-24 11:00

The following code crashes C++ with a runtime error:

#include 

using namespace std;

int main() {
    string s = \"aa\";
    for (int i = 0; i         


        
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-24 11:19

    s.length() is unsigned integer type. When you subtract 3, you make it negative. For an unsigned, it means very big.

    A workaround (valid as long the string is long up to INT_MAX) would be to do like this:

    #include 
    
    using namespace std;
    
    int main() {
    
        string s = "aa";
    
        for (int i = 0; i < static_cast (s.length() ) - 3; i++) {
    
        }
    }
    

    Which would never enter the loop.

    A very important detail is that you have probably received a warning "comparing signed and unsigned value". The problem is that if you ignore those warnings, you enter the very dangerous field of implicit "integer conversion"(*), which has a defined behaviour, but it is difficult to follow: the best is to never ignore those compiler warnings.


    (*) You might also be interested to know about "integer promotion".

提交回复
热议问题