Sams Teach Yourself C in 24 Hours (26 page)

BOOK: Sams Teach Yourself C in 24 Hours
9.36Mb size Format: txt, pdf, ePub

~x returns: 61214, i.e., 0XEF1E

In Listing 8.5, three integer variables, x, y, and z, are declared in line 6. Lines 8

ANALYSIS
and 9 set x and y to 4321 and 5678, respectively. Lines 10 and 11 then print out the values of x and y in both decimal and hex formats. The hex numbers are prefixed with 0X.

The statement in line 12 assigns the result of the operation made by the bitwise AND

operator (&) with the variables x and y. Then, line 13 displays the result in both decimal and hex formats.

11 067231861x CH08 4.10.2000 11:02 AM Page 133

Using Conditional Operators

133

Lines 14 and 15 perform the operation specified by the bitwise OR operator (|) and print out the result in both decimal and hex formats. Similarly, lines 16 and 17 give the result
8

of the operation made by the bitwise XOR operator (^).

Last, the statement in line 18 prints out the complementary value of x by using the bitwise complement operator (~). The result is displayed on the screen in both decimal and hex formats.

Note that the unsigned integer format specifier with a minimum field width of 6, %6u, and the uppercase hex format specifier with the minimum width of 4, %04X, are used in the printf() function. The unsigned integer data type is used here so that the complementary value of an integer can be shown and understood easily. More details on the unsigned data modifier are introduced in Hour 9.

Don’t confuse the
bitwise
operators & and | with the
logical
operators && and ||. For instance,

(x=1) & (y=10)

is a completely different expression from

(x=1) && (y=10)

Using Shift Operators

There are two shift operators in C. The >> operator shifts the bits of an operand to the right; the << operator shifts the bits to the left.

The general forms of the two shift operators are

x >> y

x << y

Here x is an operand that is going to be shifted. y contains the specified number of places to shift.

For instance, the expression 8 >> 2 tells the computer to shift the operand 8 to the right 2 bits, which yields the number 2 in decimal. The following:

8 >> 2 which is equivalent to (1 * 23 + 0 * 22 + 0 * 21 + 0 * 20) >> 2

produces the following:

(0 * 23 + 0 * 22 + 1 * 21 + 0 * 20) which is equivalent to 0010 (in the binary format) or 2 (in the decimal format).

11 067231861x CH08 4.10.2000 11:02 AM Page 134

134

Hour 8

Likewise, the 5 << 1 expression shifts the operand 5 to the left 1 bit, and yields 10 in decimal.

The program in Listing 8.6 prints out more results by using the shift operators.

TYPE

LISTING 8.6

Using the Shift Operators

1: /* 08L06.c: Using shift operators */

2: #include

3:

4: main()

5: {

6: int x, y, z;

7:

8: x = 255;

9: y = 5;

10: printf(“Given x = %4d, i.e., 0X%04X\n”, x, x);

11: printf(“ y = %4d, i.e., 0X%04X\n”, y, y);

12: z = x >> y;

13: printf(“x >> y yields: %6d, i.e., 0X%04X\n”, z, z);

14: z = x << y;

15: printf(“x << y yields: %6d, i.e., 0X%04X\n”, z, z);

16: return 0;

17: }

The following output is obtained by running the executable file 08L06.exe on my computer:

Given x = 255, i.e., 0X00FF

OUTPUT

y = 5, i.e., 0X0005

x >> y yields: 7, i.e., 0X0007

x << y yields: 8160, i.e., 0X1FE0

Three integer variables, x, y, and z, are declared in line 6 of Listing 8.6. x is ini-ANALYSIS tialized to 255 in line 8; y is initialized to 5 in line 9. Then, lines 10 and 11 display the values of x and y on the screen.

The statement in line 12 shifts y bits of the operand x to the right, and then assigns the result to z. Line 13 prints out the result of the shifting made in line 12. The result is 7 in decimal, or 0X0007 in hex.

Lines 14 and 15 shift the operand x to the left by y bits, and display the result on the screen too. The result of the left-shifting is 8160 in decimal, or 0x1FE0 in hex.

11 067231861x CH08 4.10.2000 11:02 AM Page 135

Using Conditional Operators

135

The operation of the shift-right operator (>>) is equivalent to dividing by
8

powers of two. In other words, the following:

x >> y

is equivalent to the following:

x / 2

Here x is a non-negative integer.

On the other hand, shifting to the left is equivalent to multiplying by powers of two; that is,

x << y

is equivalent to

x * 2

What Does
x?y:z
Mean?

The operator ?: is called the
conditional operator
, which is the only operator that takes three operands. The general form of the conditional operator is

x ? y : z

Here x, y, and z are three operand expressions. Among them, x contains the test condition, and y and z represent the two possible final values of the expression. If x evaluates to nonzero (logically true), then y is chosen; otherwise, z is the result yielded by the conditional expression. The conditional operator is used as a kind of shorthand for an if statement.

For instance, the expression

x > 0 ? ‘T’ : ‘F’

evaluates to ‘T’ if the value of x is greater than 0. Otherwise, the conditional expression evaluates to the value ‘F’.

Listing 8.7 demonstrates the usage of the conditional operator.

TYPE

LISTING 8.7

Using the Conditional Operator

1: /* 08L07.c: Using the ?: operator */

2: #include

3:

4: main()

5: {

continues

11 067231861x CH08 4.10.2000 11:02 AM Page 136

136

Hour 8

LISTING 8.7

continued

6: int x;

7:

8: x = sizeof(int);

9: printf(“%s\n”,

10: (x == 2)

11: ? “The int data type has 2 bytes.”

12: : “int doesn’t have 2 bytes.”);

13: printf(“The maximum value of int is: %d\n”,

14: (x != 2) ? ~(1 << x * 8 - 1) : ~(1 << 15) );

15: return 0;

16: }

The following output is displayed on the screen when I run the executable file 08L07.exe on my machine:

The int data type has 2 bytes

OUTPUT
The maximum value of int is: 32767

In Listing 8.7, the size of the int data type is measured first in line 8 by using the
ANALYSIS
sizeof operator, and the number of bytes is assigned to the integer variable x.

Lines 9–12 contain one statement, in which the conditional operator (?:) is used to test whether the number of bytes saved in x is equal to 2, and the result is printed. If the x == 2 expression evaluates to nonzero, the string The int data type has 2 bytes is printed out by the printf() function in the statement. Otherwise, the second string, int doesn’t have 2 bytes, is displayed on the screen.

In addition, the statement in lines 11 and 12 tries to find out the maximum value of the int data type on the current machine. The x != 2 expression is evaluated first in the statement. If the expression returns nonzero (that is, the byte number of the int data type is not equal to 2), the ~(1 << x * 8 - 1) expression is evaluated, and the result is chosen as the return value. Here the ~(1 << x * 8 - 1) expression is a general form to calculate the maximum value of the int data type, which is equivalent to 2

[ic:super](x * 8 - 1) - 1. (The complement operator, ~, and the shift operator, <<, were introduced in the previous sections of this hour.)

On the other hand, if the test condition x != 2 in line 12 returns 0, which means the value of x is indeed equal to 2, the result of the ~(1 << 15) expression is chosen. Here you may have already figured out that ~(1 << 15) is equivalent to 215–1, which is the maximum value that the 16-bit int data type can have.

The result displayed on the screen shows that the int data type on my machine is 2 bytes (or 16 bits) long, and the maximum value of the int data type is 32767.

11 067231861x CH08 4.10.2000 11:02 AM Page 137

Using Conditional Operators

137

Summary

8

In this lesson you learned the following very important logical and bit-manipulation operators in C:

• The sizeof operator evaluates to the number of bytes that a specified data type has. You can use this operator to measure the size of a data type on your machine.

• The logical AND operator (&&) yields 1 (logical true) only if both of its two operand expressions) evaluate to nonzero values. Otherwise, the operator yields 0.

• The logical OR operator (||) yields 0 only if both of its two operands evaluate to 0. Otherwise, the operator yields 1.

• The logical negation operator (!) yields 0 when its operand evaluates to nonzero, and yields 1 only if its operand evaluates to 0.

• There are six bit-manipulation operators: the bitwise AND operator (&), the bitwise OR operator (|), the bitwise XOR operator (^), the bitwise complement operator

~), the right-shift operator (>>), and the left-shift operator (<<).

• The conditional operator (?:) is the only operator in C that can take three operands.

In the next lesson you’ll learn about the data type modifiers in the C language.

Q&A

Q Why do we need the
sizeof
operator?

A
The sizeof operator can be used to measure the sizes of all data types defined in C. When you write a portable C program that needs to know the size of an integer variable, it’s a bad idea to hard-code the size based on the machine you are currently using. The better way to tell the program the size of the variable is to use the sizeof operator, which yields the size of the integer variable at runtime.

Q What’s the difference between
|
and
||
?

A
| is the bitwise OR operator that takes two operands. The | operator compares each bit of one operand to the corresponding bit in another operand. If both bits are 0, 0 is placed at the same position of the bit in the result. Otherwise, 1 is placed in the result.

On the other hand, ||, as the logical OR operator, requires two operands (or expressions). The operator yields 0 only if both of its operands evaluate to 0.

Otherwise, the operator yields 1.

11 067231861x CH08 4.10.2000 11:02 AM Page 138

138

Hour 8

Q Why is
1 << 3
equivalent to 1 * 23?

A
The 1 << 3 expression tells the computer to shift 3 bits of the operand 1 to the left. The binary format of the operand is 0001. (Note that only the lowest four bits are shown here.) After being shifted 3 bits to left, the binary number becomes 1000, which is equivalent to 1 * 23+0 * 22+0 * 21+0 * 20; that is, 1 * 23.

Q What can the conditional operator (
?:
) do?

A
If there are two possible answers under certain conditions, you can use the ?: operator to pick up one of the two answers based on the result made by testing the conditions. For instance, the expression (age > 65) ? “Retired” : “Not retired”

tells the computer that if the value of age is greater than 65, the string of Retired should be chosen; otherwise, Not retired is chosen.

Workshop

To help solidify your understanding of this hour’s lesson, you are encouraged to answer the quiz questions and finish the exercises provided in the workshop before you move to the next lesson. The answers and hints to the questions and exercises are given in Appendix D, “Answers to Quiz Questions and Exercises.”

Quiz

1. What do the (x=1) && (y=10) and (x=1) & (y=10) expressions yield, respectively?

2. Given x = 96, y = 1, and z = 69, to what does the expression !y ? x == z : y evaluate?

3. If you have two int variables x and y, with x set to the binary value 0011000000111001 and y set to the binary value 1100111111000110, what values are yielded by the two expressions ~x and ~y?

4. Given x=9, what does (x%2==0)||(x%3==0) yield? How about

(x%2==0)&&(x%3==0)?

5. Is 8 >> 3 equivalent to 8 / 23? How about 1 << 3?

Exercises

1. Given x = 0xEFFF and y = 0x1000 (that is, EFFF and 1000 as hex values), what hex values do you get by evaluating ~x and ~y?

2. Taking the values of x and y assigned in Exercise 1, write a program that prints out the values of !x and !y by using both the %d and %u formats in the printf() function.

11 067231861x CH08 4.10.2000 11:02 AM Page 139

Using Conditional Operators

139

3. Given x = 123 and y = 4, write a program that displays the results of the expressions x << y and x >> y.

8

4. Write a program that shows the values (in hex) of the expressions 0xFFFF^0x8888, 0xABCD & 0x4567, and 0xDCBA | 0x1234.

5. Use the ?: operator and the for statement to write a program that keeps taking the characters entered by the user until the character q is accounted. (Hint: Put x!=’q’

? 1 : 0 expression as the second expression in a for statement.)

11 067231861x CH08 4.10.2000 11:02 AM Page 140

Other books

Seeing Off the Johns by Rene S Perez II
The Reader by Traci Chee
Circles of Time by Phillip Rock
Decay Inevitable by Conrad Williams
MalContents by Wilbanks, David T.; Norris, Gregory L.; Thomas, Ryan C.; Chandler, Randy
The Exile Kiss by George Alec Effinger
Holiday Wishes by Nora Roberts
Just Like Fate by Cat Patrick, Suzanne Young