|
Page 5 of 8
Introduction to operators You can think of operators as a special type of function (you’ll learn that C++ operator overloading treats operators precisely that way). An operator takes one or more arguments and produces a new value. The arguments are in a different form than ordinary function calls, but the effect is the same. From your previous programming experience, you should be reasonably comfortable with the operators that have been used so far. The concepts of addition (+), subtraction and unary minus (-), multiplication (*), division (/), and assignment(=) all have essentially the same meaning in any programming language. The full set of operators is enumerated later in this chapter. Precedence
Operator precedence defines the order in which an expression evaluates when several different operators are present. C and C++ have specific rules to determine the order of evaluation. The easiest to remember is that multiplication and division happen before addition and subtraction. After that, if an expression isn’t transparent to you it probably won’t be for anyone reading the code, so you should use parentheses to make the order of evaluation explicit. For example: A = X + Y - 2/2 + Z; has a very different meaning from the same statement with a particular grouping of parentheses: A = X + (Y - 2)/(2 + Z); (Try evaluating the result with X = 1, Y = 2, and Z = 3.) Auto increment and decrement C, and therefore C++, is full of shortcuts. Shortcuts can make code much easier to type, and sometimes much harder to read. Perhaps the C language designers thought it would be easier to understand a tricky piece of code if your eyes didn’t have to scan as large an area of print. One of the nicer shortcuts is the auto-increment and auto-decrement operators. You often use these to change loop variables, which control the number of times a loop executes. The auto-decrement operator is ‘--’ and means “decrease by one unit.” The auto-increment operator is ‘++’ and means “increase by one unit.” If A is an int, for example, the expression ++A is equivalent to (A = A + 1). Auto-increment and auto-decrement operators produce the value of the variable as a result. If the operator appears before the variable, (i.e., ++A), the operation is first performed and the resulting value is produced. If the operator appears after the variable (i.e. A++), the current value is produced, and then the operation is performed. For example: //: C03:AutoIncrement.cpp // Shows use of auto-increment // and auto-decrement operators. #include <iostream> using namespace std;
int main() { int i = 0; int j = 0; cout << ++i << endl; // Pre-increment cout << j++ << endl; // Post-increment cout << --i << endl; // Pre-decrement cout << j-- << endl; // Post decrement } ///:~ If you’ve been wondering about the name “C++,” now you understand. It implies “one step beyond C.” Introduction to data types Data types define the way you use storage (memory) in the programs you write. By specifying a data type, you tell the compiler how to create a particular piece of storage, and also how to manipulate that storage. Data types can be built-in or abstract. A built-in data type is one that the compiler intrinsically understands, one that is wired directly into the compiler. The types of built-in data are almost identical in C and C++. In contrast, a user-defined data type is one that you or another programmer create as a class. These are commonly referred to as abstract data types. The compiler knows how to handle built-in types when it starts up; it “learns” how to handle abstract data types by reading header files containing class declarations (you’ll learn about this in later chapters). Basic built-in types The Standard C specification for built-in types (which C++ inherits) doesn’t say how many bits each of the built-in types must contain. Instead, it stipulates the minimum and maximum values that the built-in type must be able to hold. When a machine is based on binary, this maximum value can be directly translated into a minimum number of bits necessary to hold that value. However, if a machine uses, for example, binary-coded decimal (BCD) to represent numbers, then the amount of space in the machine required to hold the maximum numbers for each data type will be different. The minimum and maximum values that can be stored in the various data types are defined in the system header files limits.h and float.h (in C++ you will generally #include <climits> and <cfloat> instead). C and C++ have four basic built-in data types, described here for binary-based machines. A char is for character storage and uses a minimum of 8 bits (one byte) of storage, although it may be larger. An int stores an integral number and uses a minimum of two bytes of storage. The float and double types store floating-point numbers, usually in IEEE floating-point format. float is for single-precision floating point and double is for double-precision floating point. As mentioned previously, you can define variables anywhere in a scope, and you can define and initialize them at the same time. Here’s how to define variables using the four basic data types: //: C03:Basic.cpp // Defining the four basic data // types in C and C++
int main() { // Definition without initialization: char protein; int carbohydrates; float fiber; double fat; // Simultaneous definition & initialization: char pizza = 'A', pop = 'Z'; int dongdings = 100, twinkles = 150, heehos = 200; float chocolate = 3.14159; // Exponential notation: double fudge_ripple = 6e-4; } ///:~ The first part of the program defines variables of the four basic data types without initializing them. If you don’t initialize a variable, the Standard says that its contents are undefined (usually, this means they contain garbage). The second part of the program defines and initializes variables at the same time (it’s always best, if possible, to provide an initialization value at the point of definition). Notice the use of exponential notation in the constant 6e-4, meaning “6 times 10 to the minus fourth power.” bool, true, & false Before bool became part of Standard C++, everyone tended to use different techniques in order to produce Boolean-like behavior. These produced portability problems and could introduce subtle errors. The Standard C++ bool type can have two states expressed by the built-in constants true (which converts to an integral one) and false (which converts to an integral zero). All three names are keywords. In addition, some language elements have been adapted: | | | | | Take bool arguments and produce bool results. | | | | | | Conditional expressions convert to bool values. | | | First operand converts to bool value. | Because there’s a lot of existing code that uses an int to represent a flag, the compiler will implicitly convert from an int to a bool (nonzero values will produce true while zero values produce false). Ideally, the compiler will give you a warning as a suggestion to correct the situation. An idiom that falls under “poor programming style” is the use of ++ to set a flag to true. This is still allowed, but deprecated, which means that at some time in the future it will be made illegal. The problem is that you’re making an implicit type conversion from bool to int, incrementing the value (perhaps beyond the range of the normal bool values of zero and one), and then implicitly converting it back again. Pointers (which will be introduced later in this chapter) will also be automatically converted to bool when necessary. Specifiers
Specifiers modify the meanings of the basic built-in types and expand them to a much larger set. There are four specifiers: long, short, signed, and unsigned. long and short modify the maximum and minimum values that a data type will hold. A plain int must be at least the size of a short. The size hierarchy for integral types is: short int, int, long int. All the sizes could conceivably be the same, as long as they satisfy the minimum/maximum value requirements. On a machine with a 64-bit word, for instance, all the data types might be 64 bits. The size hierarchy for floating point numbers is: float, double, and long double. “long float” is not a legal type. There are no short floating-point numbers. The signed and unsigned specifiers tell the compiler how to use the sign bit with integral types and characters (floating-point numbers always contain a sign). An unsigned number does not keep track of the sign and thus has an extra bit available, so it can store positive numbers twice as large as the positive numbers that can be stored in a signed number. signed is the default and is only necessary with char; char may or may not default to signed. By specifying signed char, you force the sign bit to be used. The following example shows the size of the data types in bytes by using the sizeof operator, introduced later in this chapter: //: C03:Specify.cpp // Demonstrates the use of specifiers #include <iostream> using namespace std;
int main() { char c; unsigned char cu; int i; unsigned int iu; short int is; short iis; // Same as short int unsigned short int isu; unsigned short iisu; long int il; long iil; // Same as long int unsigned long int ilu; unsigned long iilu; float f; double d; long double ld; cout << "\n char= " << sizeof(c) << "\n unsigned char = " << sizeof(cu) << "\n int = " << sizeof(i) << "\n unsigned int = " << sizeof(iu) << "\n short = " << sizeof(is) << "\n unsigned short = " << sizeof(isu) << "\n long = " << sizeof(il) << "\n unsigned long = " << sizeof(ilu) << "\n float = " << sizeof(f) << "\n double = " << sizeof(d) << "\n long double = " << sizeof(ld) << endl; } ///:~ Be aware that the results you get by running this program will probably be different from one machine/operating system/compiler to the next, since (as mentioned previously) the only thing that must be consistent is that each different type hold the minimum and maximum values specified in the Standard. When you are modifying an int with short or long, the keyword int is optional, as shown above.
|