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

前端 未结 8 965
遇见更好的自我
遇见更好的自我 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:09

    The reason is the same as int a = 1000000000; long long b = a * 100000000; would give error. When compilers multiplies these numbers it evaluates it as ints, since a and literal 1000000000 are ints, and since 10^18 is much more large than the upper bound of int, it will give error. In your case we have s.length() - 3, as s.length() is unsigned int, it cant be negative, and since s.length() - 3 is evaluated as unsigned int, and its value is -1, it gives error here too.

提交回复
热议问题