Saturday, October 19, 2013

example of signed and unsigned integers

This next code highlights the difference between signed and unsigned integers and shows how you can end up "going round the houses" when you go beyond the upper limits for the different variables - with this happening for both signed and unsigned with different results.

sam is the more normal signed integer while sue is unsigned (and hence can have much higher positive values but not negative values.

IMPORTANT NOTE - for unsigned integers the above "round the houses" behavior is guaranteed, but not for unsigned integers. int main() { short sam = SHRT_MAX; unsigned short sue = sam; cout << "Sam has " << sam << " dollars ans Sue has " << sue << " dollars deposited" << endl; cout << "add usd 1 to each account" << endl << "now "; sam = sam + 1; sue = sue + 1; cout << "sam has " << sam << "dollars " << "sue has " << sue << " dollars - poor sam. Lets put to zero next" <<endl; sam = ZERO; sue = ZERO; cout << "now sam has " << sam << " dollars and sue has " << sue << " dollars" <<endl; cout << "take one dollar from each account" <<endl; sam = sam - 1; sue = sue - 1; cout << "now sam has " << sam << " dollars and sue has " << sue << " dollars" << endl; cout << "lucky sue" << endl; return 0; }

No comments:

Post a Comment