Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does while(i--) s+= a[i]; contain undefined behavior in C and C++?

Consider simple code:

#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;
}

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?

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

Update

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.

like image 241
George Sovetov Avatar asked Apr 08 '16 11:04

George Sovetov


People also ask

What are the advantages of undefined behavior in C++?

Advantages of Undefined Behavior. C and C++ have undefined behaviors because it allows compilers to avoid lots of checks. Suppose a set of code with greater performing array need not keep a look at the bounds, which avoid the needs for complex optimization pass to check such conditions outside loops.

Is I = 3 an undefined behavior?

As it stands, it is undefined behaviour according to the standard ( Wikipedia ), so it's even free to do this: i = 3; system ("sudo rm -rf /"); // DO NOT TRY THIS AT HOME … OR AT WORK … OR ANYWHERE. Show activity on this post. No, we don't use the term "undefined behavior" when it can simply lead to more than one arithmetical result.

What happens when the compiler triggers undefined behavior?

Then undefined behavior is triggered, and the compiler can do literally anything. For convenience, the compiler chooses to treat this case the same as the well-defined-behavior case, so we can just return false.

What does I = I++ mean in programming?

Undefined behavior means completely unpredictable and unlimited consequences, like formatting the hard drive on your computer or simply making your program to crash. And i = i++ is undefined behavior.


1 Answers

This code doesn't invoke undefined behavior. The loop will be terminated once i becomes 0.

For unsigned int, there is no integer over/underflow. The effect will be same with i as signed except there will no wrapping in this case.

like image 106
haccks Avatar answered Nov 14 '22 18:11

haccks