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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With