This is an update of a post that originally appeared onĀ October 16, 2015.
Originally I provided this post to correct an example in a previous edition of the book. Now I’m providing it to clarify that same example to a greater degree and answer reader input. The Going Overboard section on page 64 of C++ All-In-One for Dummies, 4th Edition talks about the problems that can occur when you try to stuff a number that’s too large into a specific data type. The problem with the example shown:
cout << 12345678 * 100 / 2 * 3 * 3 << endl;
is that while it does display a warning message, the warning really doesn’t get the point across. In order to see the example as originally intended, you need to change the code to read:
long MyLong = 12345678 * 100 / 2 * 3 * 3;
cout << MyLong << endl;
The code will now produce a warning and you can see why in a clearer way, just as described in the book, because the data type isn’t ambiguous any longer. In both cases you see a warning message of:
warning: integer overflow in expression of type 'int' results in '1260587804'
One of the ways to overcome this problem is to ensure that you use the correct sized variable in the first place. The following code doesn’t produce a warning message because of the use of auto
(telling the compiler to choose the correct variable type automatically) and ll
(telling the compiler to use a long long
variable for the calculation).
auto AutoSize = 12345678ll * 100 / 2 * 3 * 3;
cout << AutoSize << endl;
A number of readers were happy that I pointed the problem out, but wanted to see a fix for the problem as well. When you run the example with the additional code, you see outputs of:
1260587804
1260587804
5555555100
Only the third answer is the correct one and it points out the need to pay attention to both warnings and errors as you code. Please let me know if you have any questions or concerns about this example at [email protected].