Home >Backend Development >C++ >Why Does This Loop Overflow and Produce Unexpected Output?
Why does this loop produce "warning: iteration 3u invokes undefined behavior" and output more than 4 lines?
The code in question:
#include <iostream> int main() { for (int i = 0; i < 4; ++i) std::cout << i * 1000000000 << std::endl; }
generates the following warning:
warning: iteration 3u invokes undefined behavior [-Waggressive-loop-optimizations] std::cout << i * 1000000000 << std::endl; ^
This warning stems from a signed integer overflow that occurs in the statement:
i * 1000000000
The multiplication of i (an int data type) by 1000000000 results in an integer overflow because 1000000000 is too large to fit within the range of an int variable. Consequently, the value of i becomes undefined, and any subsequent operations on i (such as outputting it to the console) may produce unexpected results.
In this specific case, the loop continues iterating and produces output beyond the intended four iterations because the loop condition i < 4 evaluates to true. However, due to the integer overflow, the i value has become corrupted, and the loop continues to iterate until the output buffer is full.
To resolve this issue, you must either adjust the loop's termination condition to account for the overflow or use an integer data type wide enough to handle the result of the multiplication.
The above is the detailed content of Why Does This Loop Overflow and Produce Unexpected Output?. For more information, please follow other related articles on the PHP Chinese website!