warning: iteration 5u invokes undefined behavior [-Waggressive-loop-optimizations]
Solution 1
If index is out of bound, I should be just getting junk result right. But why endless!
When the for
loop ends, the value if i
is 5
.
In the first iteration of the while
loop, you access a[5]
, which leads to undefined behavior. After that, anything can happen.
Also, the while
loop is wrong on another account. If undefined behavior was not invoked in the loop, t will execute the loop 6
times, for values of i
equal to 5
, 4
, 3
, 2
, 1
, and 0
.
Executing i--;
before entering the while
loop fixes both problems.
Solution 2
volatile i
helps avoiding this error message.
Rajesh
Updated on June 13, 2022Comments
-
Rajesh almost 2 years
In the below code, I am not sure why I get the warning: iteration 5u invokes undefined behavior [-Waggressive-loop-optimizations] when I comment the printf(" "); statement in the for loop. How a printf statement contributes to this warning?.
Secondly, this code go to endless loop. I know array index is outside the limit when entering while loop. But when i goes negative, while loop should have terminated. But not happening. If i-- is done before entering while loop, there is no issue. If index is out of bound, I should be just getting junk result right. But why endless!
int main (void) { int a[]={4,6,8,2,7}; int i=0; int size = sizeof(a)/sizeof(a[0]); for(i=0;i<size;i++) { // printf(" "); } // i--; // doing i-- works fine. while(i>=0) { printf("%d\t",a[i]); i--; } return(0); }
-
Rajesh almost 8 yearsSo you mean to say if array index goes out of bound, it is not only printing junk value, but also misbehave in any manner. But why compilation warning is pointing to for loop? Why warning disappears if I just add just a printf() statement inside the for loop? So compiler behaviour is also undefined in addition to runtime undefined behavior?
-
R Sahu almost 8 years@Rajesh, "yes" to the first question. I don't have answers to the other questions.
-
GeorgDangl about 7 yearsHi, and welcome to the site! Could you add a bit of explanation why the
volatile
keyword solves this problem?