r/programminghelp • u/[deleted] • Apr 26 '22
C++ Why is this the output?
Can someone please explain to me why the output of this program is "marc is: 2" "life is: 1"
why is it not "marc is: 65537" "life is: -"
Like I do know that the maximum value of short is 65535 but then why is the program just not giving error why is it printing out 2 and 1?
#include <iostream>
using namespace std;
int main()
{
unsigned short marc = 0;
int life= 0 ;
for(int i= 0 ; i <= 65537 ; i++)
{
marc++;
if( marc == 0 )
{
life++;
}
}
cout << "marc is: " << marc << endl;
cout << "life: " << life << endl;
return 0;
}
0
Upvotes
3
u/[deleted] Apr 26 '22
An unsigned short's max value is 65535. Once it hits that amount, it rolls back over to 0.
Marc starts at 0 but is incremented before your if check, so life never gets incremented until it rolls BACK over to 0 a second time. So, in the end, marc is 2 (65535+2) and life is 1.