C ++在带有负表达式的“ for”循环中崩溃 [英] C++ crashes in a 'for' loop with a negative expression

查看:101
本文介绍了C ++在带有负表达式的“ for”循环中崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码使C ++崩溃,并出现运行时错误:

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

#include <string>

using namespace std;

int main() {
    string s = "aa";
    for (int i = 0; i < s.length() - 3; i++) {

    }
}

虽然此代码不会崩溃:

#include <string>

using namespace std;

int main() {
    string s = "aa";
    int len = s.length() - 3;
    for (int i = 0; i < len; i++) {

    }
}

我只是不知道如何解释它。

I just don't have any idea how to explain it. What could be the reason for this behavior?

推荐答案

s.length()是无符号整数类型。当您减去3时,将其设为负数。对于 unsigned ,这表示很大

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

一种解决方法(有效期为该字符串最长为INT_MAX)将是这样的:

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

#include <string>

using namespace std;

int main() {

    string s = "aa";

    for (int i = 0; i < static_cast<int> (s.length() ) - 3; i++) {

    }
}

永远不会进入循环。

一个非常重要的细节是,您可能会收到警告比较有符号和无符号值。问题是,如果忽略这些警告,则会输入非常危险的 implicit 字段整数转换 (*),它具有定义的行为,但是很难遵循:最好是永远不要忽略那些编译器警告。

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.



(*)您可能也想知道整数提升

这篇关于C ++在带有负表达式的“ for”循环中崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆