while(i--) s+= a[i];在 C 和 C++ 中包含未定义的行为? [英] Does while(i--) s+= a[i]; contain undefined behavior in C and C++?

查看:39
本文介绍了while(i--) s+= a[i];在 C 和 C++ 中包含未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑简单的代码:

#include "stdio.h"

#define N 10U

int main() {
    int a[N] = {0};
    unsigned int i = N;
    int s = 0;

    // Fill a

    while(i--)
        s += a[i];

    printf("Sum is %d\n", s);

    return 0;
}

由于整数下溢,while 循环是否包含未定义的行为?编译器是否有权因此假设 while 循环条件始终为真并以无限循环结束?

Does while loop contain undefined behavior because of integer underflow? Do compilers have right to assume that while loop condition is always true because of that and end up with endless loop?

如果 isigned int 会怎样?它不包含与数组访问相关的陷阱吗?

What if i is signed int? Doesn't it contain pitfalls related to array access?

更新

我多次运行这个和类似的代码,它运行良好.此外,它是向后迭代数组和向量的流行方法.我问这个问题是为了确保从标准的角度来看这种方式是可以的.

I run this and similar code many times and it worked fine. Moreover, it's popular way to iterate over arrays and vectors backwards. I'm asking this question to make sure that this way is OK from point of view of standard.

乍一看,显然不是无限的.另一方面,有时编译器可以优化"掉一些条件和代码,假设代码不包含未定义的行为.它可能导致无限循环和其他不必要的后果.请参阅.

At glance, it's obviously not infinite. On other hand, sometimes compiler can "optimize" away some conditions and code assuming that code contains no undefined behavior. It can lead to infinite loops and other unwanted consequences. See this.

推荐答案

由于整数下溢,while 循环是否包含未定义的行为?

Does while loop contain undefined behavior because of integer underflow?

不,上溢/下溢只是有符号整数情况下的未定义行为.

No, overflow/underflow is only undefined behavior in case of signed integers.

编译器是否有权因此假设 while 循环条件始终为真并以无限循环结束?

Do compilers have right to assume that while loop condition is always true because of that and end up with endless loop?

不,因为表达式最终会变成零.

No, because the expression will eventually turn out to be zero.

如果我是signed int怎么办?它不包含与数组访问相关的陷阱吗?

What if i is signed int? Doesn't it contain pitfalls related to array access?

如果它是有符号的并且上溢/下溢,则会调用未定义的行为.

If it is signed and over/underflows, you invoke undefined behavior.

这篇关于while(i--) s+= a[i];在 C 和 C++ 中包含未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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