A+ A-

Integer Values in C++

C++ supports a number of numeric and non-numeric values. In particular, C++ programs can use integer values. It is easy to write a C++ program that prints the number four, as example 1


[code type="Example 1"]#include <iostream>
 using namespace std;
 int main()
{ cout << 4 << endl; }
[/code]

[code type="Example2"]#include <iostream>
 using namespace std;
int main()
{ cout << "4" << endl; }
[/code]

Both programs behave identically, but example 1 prints the value of the number four, while Listing 3.2 (number4-alt.cpp) prints a message containing the digit four. The distinction here seems unimportant, but the presence or absence of the quotes can make a big difference in the output. In C++ source code, integers may not contain commas. This means we must write the number two thousand, four hundred sixty-eight as 2468, not 2,468. In mathematics, integers are unbounded; said another way, the set of mathematical integers is infinite. In C++ the range of integers is limited because all computers have a finite amount of memory. The exact range of integers supported depends on the computer system and particular C++ compiler. C++ on most 32-bit computer systems can represent integers in the range −2,147,483,648 to +2,147,483,647.

What happens if you exceed the range of C++ integers?

[code type="Exeed cpp"]#include <iostream>
using namespace std;
int main()
{ cout << -3000000000 << endl; }
[/code]

Negative three billion is too large for 32-bit integers, however, and the program’s output is obviously wrong:

[code type="Result"]1294967296[/code]

The number printed was not even negative! Most C++ compilers will issue a warning about this statement. secrefsec:expressionsarithmetic.errors explores errors vs. warnings in more detail. If the compiler finds an error in the source, it will not generate the executable code. A warning indicates a potential problem and does not stop the compiler from producing an executable program. Here we see that the programmer should heed this warning because the program’s execution produces meaningless output. This limited range of values is common among programming languages since each number is stored in a fixed amount of memory. Larger numbers require more storage in memory. In order to model the infinite set of mathematical integers an infinite amount of memory would be needed!

C++ supports a number of numeric and non-numeric values. In particular, C++ programs can use integer values. It is easy to write a C++ program that prints the number four, as example 1