The Assignment Operator
The assignment operator is the equal sign (=). Its use in programming is somewhat different from its use in regular math. If you writex = y;in a C program, it doesn't mean "x is equal to y." Instead, it means "assign the value of y to x." In a C assignment statement, the right side can be any expression, and the left side must be a variable name. Thus, the form is as follows:
variable = expression;When executed, expression is evaluated, and the resulting value is assigned to variable.
Mathematical Operators
C's mathematical operators perform mathematical operations such as addition and subtraction. C has two unary mathematical operators and five binary mathematical operators.Unary Mathematical Operators
The unary mathematical operators are so named because they take a single operand. C has two unary mathematical operators, listed in Table 4.1.Table 4.1. C's unary mathematical operators.
Operator | Symbol | Action | Examples |
Increment | ++ | Increments the operand by one | ++x, x++ |
Decrement | -- | Decrements the operand by one | --x, x-- |
++x; --y;are the equivalent of these statements:
x = x + 1; y = y - 1;You should note from Table 4.1 that either unary operator can be placed before its operand (prefix mode) or after its operand (postfix mode). These two modes are not equivalent. They differ in terms of when the increment or decrement is performed:
- When used in prefix mode, the increment and decrement operators modify their operand before it's used.
- When used in postfix mode, the increment and decrement operators modify their operand after it's used.
x = 10; y = x++;After these statements are executed, x has the value 11, and y has the value 10. The value of x was assigned to y, and then x was incremented. In contrast, the following statements result in both y and x having the value 11. x is incremented, and then its value is assigned to y.
x = 10; y = ++x;Remember that = is the assignment operator, not a statement of equality. As an analogy, think of = as the "photocopy" operator. The statement y = x means to copy x into y. Subsequent changes to x, after the copy has been made, have no effect on y.
Listing 4.1 illustrates the difference between prefix mode and postfix mode.
Listing 4.1. UNARY.C: Demonstrates prefix and postfix modes.
/* Demonstrates unary operator prefix and postfix modes */ #includeint a, b; main() {
/* Set a and b both equal to 5 */
a = b = 5;
/* Print them, decrementing each time. */
/* Use prefix mode for b, postfix mode for a */
printf("\n%d %d", a--, --b); printf("\n%d %d", a--, --b);
printf("\n%d %d", a--, --b);
printf("\n%d %d", a--, --b);
printf("\n%d %d\n", a--, --b); return 0;
}ANALYSIS: This program declares two variables, a and b, in line 5. In line 11, the variables are set to the value of 5. With the execution of each printf() statement (lines 16 through 20), both a and b are decremented by 1. After a is printed, it is decremented, whereas b is decremented before it is printed.
Binary Mathematical Operators
C's binary operators take two operands. The binary operators, which include the common mathematical operations found on a calculator, are listed in Table 4.2.Table 4.2. C's binary mathematical operators.
Operator | Symbol | Action | Example |
Addition | + | Adds two operands | x + y |
Subtraction | - | Subtracts the second operand from the first operand | x - y |
Multiplication | * | Multiplies two operands | x * y |
Division | / | Divides the first operand by the second operand | x / y |
Modulus | % | Gives the remainder when the first operand is divided by the second operand | x % y |
100 modulus 9 equals 1 10 modulus 5 equals 0 40 modulus 6 equals 4Listing 4.2 illustrates how you can use the modulus operator to convert a large number of seconds into hours, minutes, and seconds.
Listing 4.2. SECONDS.C: Demonstrates the modulus operator.
/* Illustrates the modulus operator. */ /* Inputs a number of seconds, and converts to hours, */ /* minutes, and seconds. */ #include/* Define constants */ #define SECS_PER_MIN 60 #define SECS_PER_HOUR 3600 unsigned seconds, minutes, hours, secs_left, mins_left; main() { /* Input the number of seconds */ printf("Enter number of seconds (< 65000): "); scanf("%d", &seconds); hours = seconds / SECS_PER_HOUR; minutes = seconds / SECS_PER_MIN; mins_left = minutes % SECS_PER_MIN; secs_left = seconds % SECS_PER_MIN; printf("%u seconds is equal to ", seconds); printf("%u h, %u m, and %u s\n", hours, mins_left, secs_left); return 0;
}ANALYSIS: SECONDS.C follows the same format that all the previous programs have followed. Lines 1 through 3 provide some comments to state what the program does. Line 4 is white space to make the program more readable. Just like the white space in statements and expressions, blank lines are ignored by the compiler. Line 5 includes the necessary header file for this program. Lines 9 and 10 define two constants, SECS_PER_MIN and SECS_PER_HOUR, that are used to make the statements in the program easier to read. Line 12 declares all the variables that will be used. Some people choose to declare each variable on a separate line rather than all on one. As with many elements of C, this is a matter of style. Either method is correct.
Line 14 is the main() function, which contains the bulk of the program. To convert seconds to hours and minutes, the program must first get the values it needs to work with. To do this, line 18 uses the printf() function to display a statement on-screen, followed by line 19, which uses the scanf() function to get the number that the user entered. The scanf() statement then stores the number of seconds to be converted into the variable seconds. The printf() and scanf() functions are covered in more detail on Day 7, "Fundamentals of Input and Output." Line 21 contains an expression to determine the number of hours by dividing the number of seconds by the constant SECS_PER_HOUR. Because hours is an integer variable, the remainder value is ignored. Line 22 uses the same logic to determine the total number of minutes for the seconds entered. Because the total number of minutes figured in line 22 also contains minutes for the hours, line 23 uses the modulus operator to divide the hours and keep the remaining minutes. Line 24 carries out a similar calculation for determining the number of seconds that are left. Lines 26 and 27 are similar to what you have seen before. They take the values that have been calculated in the expressions and display them. Line 29 finishes the program by returning 0 to the operating system before exiting.
Operator Precedence and Parentheses
In an expression that contains more than one operator, what is the order in which operations are performed? The importance of this question is illustrated by the following assignment statement:x = 4 + 5 * 3;Performing the addition first results in the following, and x is assigned the value 27:
x = 9 * 3;In contrast, if the multiplication is performed first, you have the following, and x is assigned the value 19:
x = 4 + 15;Clearly, some rules are needed about the order in which operations are performed. This order, called operator precedence, is strictly spelled out in C. Each operator has a specific precedence. When an expression is evaluated, operators with higher precedence are performed first. Table 4.3 lists the precedence of C's mathematical operators. Number 1 is the highest precedence and thus is evaluated first.
Table 4.3. The precedence of C's mathematical operators.
Operators | Relative Precedence |
++ -- | 1 |
* / % | 2 |
+ - | 3 |
- Unary increment and decrement
- Multiplication, division, and modulus
- Addition and subtraction
12 % 5 * 2The expression evaluates to 4 (12 % 5 evaluates to 2; 2 times 2 is 4).
Returning to the previous example, you see that the statement x = 4 + 5 * 3; assigns the value 19 to x because the multiplication is performed before the addition.
What if the order of precedence doesn't evaluate your expression as needed? Using the previous example, what if you wanted to add 4 to 5 and then multiply the sum by 3? C uses parentheses to modify the evaluation order. A subexpression enclosed in parentheses is evaluated first, without regard to operator precedence. Thus, you could write
x = (4 + 5) * 3;The expression 4 + 5 inside parentheses is evaluated first, so the value assigned to x is 27.
You can use multiple and nested parentheses in an expression. When parentheses are nested, evaluation proceeds from the innermost expression outward. Look at the following complex expression:
x = 25 - (2 * (10 + (8 / 2)));The evaluation of this expression proceeds as follows:
- 1. The innermost expression, 8 / 2, is evaluated first, yielding the value 4:
25 - (2 * (10 + 4))
- 2. Moving outward, the next expression, 10 + 4, is evaluated, yielding the value 14:
25 - (2 * 14)
- 3. The last, or outermost, expression, 2 * 14, is evaluated, yielding the value 28:
25 - 28
- 4. The final expression, 25 - 28, is evaluated, assigning the value -3 to the variable x:
You might want to use parentheses in some expressions for the sake of clarity, even when they aren't needed for modifying operator precedence. Parentheses must always be in pairs, or the compiler generates an error message.x = -3
Order of Subexpression Evaluation
As was mentioned in the previous section, if C expressions contain more than one operator with the same precedence level, they are evaluated left to right. For example, in the expressionw * x / y * zw is multiplied by x, the result of the multiplication is then divided by y, and the result of the division is then multiplied by z.
Across precedence levels, however, there is no guarantee of left-to-right order. Look at this expression:
w * x / y + z / yBecause of precedence, the multiplication and division are performed before the addition. However, C doesn't specify whether the subexpression w * x / y is to be evaluated before or after z / y. It might not be clear to you why this matters. Look at another example:
w * x / ++y + z / yIf the left subexpression is evaluated first, y is incremented when the second expression is evaluated. If the right expression is evaluated first, y isn't incremented, and the result is different. Therefore, you should avoid this sort of indeterminate expression in your programming.
Near the end of this chapter, the section "Operator Precedence Revisited" lists the precedence of all of C's operators.
DO use parentheses to make the order of expression evaluation clear. DON'T overload an expression. It is often more clear to break an expression into two or more statements. This is especially true when you're using the unary operators (--) or (++).
Relational Operators
C's relational operators are used to compare expressions, asking questions such as, "Is x greater than 100?" or "Is y equal to 0?" An expression containing a relational operator evaluates to either true (1) or false (0). C's six relational operators are listed in Table 4.4.Table 4.5 shows some examples of how relational operators might be used. These examples use literal constants, but the same principles hold with variables.
NOTE: "True" is considered the same as "yes," which is also considered the same as 1. "False" is considered the same as "no," which is considered the same as 0.
Table 4.4. C's relational operators.
Operator | Symbol | Question Asked | Example |
Equal | == | Is operand 1 equal to operand 2? | x == y |
Greater than | > | Is operand 1 greater than operand 2? | x > y |
Less than | < | Is operand 1 less than operand 2? | x < y |
Greater than or equal to | >= | Is operand 1 greater than or equal to operand 2? | x >= y |
Less than or equal to | <= | Is operand 1 less than or equal to operand 2? | x <= y |
Not equal | != | Is operand 1 not equal to operand 2? | x != y |
Table 4.5. Relational operators in use.
Expression | How It Reads | What It Evaluates To |
5 == 1 | Is 5 equal to 1? | 0 (false) |
5 > 1 | Is 5 greater than 1? | 1 (true) |
5 != 1 | Is 5 not equal to 1? | 1 (true) |
(5 + 10) == (3 * 5) | Is (5 + 10) equal to (3 * 5)? | 1 (true) |
DO learn how C interprets true and false. When working with relational operators, true is equal to 1, and false is equal to 0. DON'T confuse ==, the relational operator, with =, the assignment operator. This is one of the most common errors that C programmers make.
Tidak ada komentar:
Posting Komentar