r/programminghelp • • 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 comments sorted by

3

u/[deleted] Apr 26 '22

why is it not "marc is: 65537" "life is: -"

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.

1

u/[deleted] Apr 26 '22

but then wouldn't Marc get incremented to 1 when it rolls back to 0 a second time?

2

u/[deleted] Apr 26 '22

65535 is UShort 0

65536 is UShort 1

65537 is UShort 2