A Note About Unsigned Integers

In Fig. 4.7, line 46 declared the variable gradeCounter as an unsigned int because it can assume only the values from 1 through 11 (11 terminates the loop), which are all positive values. In general, counters that should store only non-negative values should be declared with unsigned types. Variables of unsigned integer types can represent values from 0 to approximately twice the positive range of the corresponding signed integer types. You can determine your platform’s maximum unsigned int value with the constant UINT_MAX from <climits>.

Figure 4.7 could have also declared as unsigned int the variables grade, total and average. Grades are normally values from 0 to 100, so the total and average should each be greater than or equal to 0. We declared those variables as ints because we can’t control what the user actually enters—the user could enter negative values. Worse yet, the user could enter a value that’s not even a number. (We’ll show how to deal with such erroneous inputs later in the book.)

Sometimes sentinel-controlled loops use intentionally invalid values to terminate a loop. For example, in line 56 of Fig. 4.10, we terminate the loop when the user enters the sentinel -1 (an invalid grade), so it would be improper to declare variable grade as an unsigned int. As you’ll see, the end-of-file (EOF) indicator—which is introduced in the next chapter and is often used to terminate sentinel-controlled loops—is also normally implemented internally in the compiler as a negative number.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.107.181