Your code will keep on incrementing the variable k
because the condition k > j
is true. At some point k
will get equal to the maximum int
value supported on your system. When you do k++
in the next loop, the result is not representable as an int
. This is called integer overflow and according to the standard, the code has undefined behavior. As it is undefined behavior we can't say what will happen in general - it is system specific.
On many system the result of incrementing the maximum int
value will result in the minimum int
value. On such systems your code is equivalent to the code:
#include<iostream>
#include <limits>
int main()
{
int j = std::numeric_limits<int>::max();
int k = j + 1;
std::cout << j << std::endl << k << std::endl;
return 0;
}
On my system the output is:
2147483647
-2147483648
But do not expect this to hold for all systems. On other systems the program may crash, or enter an endless loop or do whatever... it is undefined by the standard.
A better way to write the code so that it will work on all systems is:
#include<iostream>
#include <limits>
int main()
{
int j = std::numeric_limits<int>::max();
int k = std::numeric_limits<int>::min();
std::cout << j << std::endl << k << std::endl;
return 0;
}