Physics and Astronomy |
Back to top
On this page
Contents Appendix: more details about integersThe occasional appendices and optional examples in this module are for advanced material that you will not need for this module. They are intended for enthusiastic students who are interested in going further in programming for its own sake. Length of integer variablesC is designed to run on anything from a tiny one-chip micro-controllers with a few thousand bytes of memory (or less!) upwards and so integer variables are available that use anything from one to eight bytes each. One or two-byte integers are typically used for systems with very little memory. Most systems default to four-byte integers but provide for eight-byte integers when rewuired. Examples where we would need to use an eight-byte integer include:
Length of integer typesUnfortunately the numbers of bytes per type is not standardised, the only guarantee being that each type has a certain minimum length:
NB "short int" can just be abbreviated to "short", "long int" to "long",etc. If you are really need to know the length of your system's integer types then this size checking program will tell you. Division of negative integersIn the main notes, we very slightly skipped over division of negative integers because they are hardly ever used. However... We know that 5/2 equals 2 but should -5/2 be -2 or -3?
The fact that negative-integer division and remainder used not to be uniquely defined shows just how rare it is. Early versions of C allowed the compiler to choose either option (!); that choice has now been removed and the rule is now option (i): negative numbers round towards zero:-5/2 equals 5/-2 equals -2 -j/k equals j/-k equals -(j/k) -5 % 2 equals 5 % -2 equals -1 -j % k equals j % -k equals -(j % k) Floating-point to integer conversionC adopts exactly the same policy when dealing with statements like: x = 1.82; j = x; the whole point of integers is that they are not allowed to have fractional values so j is assigned the value 1. Again note that this is not necessarily the nearest integer. Negative values are also handled in the same way as integer division, rounding towards zero: x = -1.82; j = x; gives j the value of -1; Finally, if we do ever find ourselves converting floating-point expressions to integers we must be be aware that rounding errors can tip the result by one from the mathematically correct result when that result is exactly, or close to, an integer |