13. Are There More Operators?

Additional C Operators

image

Have patience! You’ve learned about almost all of the C operators. With the exception of a few more advanced operators that you’ll read about in Chapter 24, “What’s the Point?,” this chapter rounds out the order of operators table and explains conditional operators, increment operators, and decrement operators.

C’s operators sometimes substitute for more wordy commands that you would use in other programming languages. Not only can an assortment of operators speed your program development time, they also compile more efficiently and run faster than commands. The C operators do a lot to make C the efficient language that it is.

Goodbye if-else; Hello Conditional

The conditional operator is the only C operator that requires three arguments. Whereas division, multiplication, and most of the others require two values to work, the conditional operator requires three. Although the format of the conditional operator looks complex, you will see that it streamlines some logic and is actually straightforward to use.

The conditional operator looks like this: ?:. Here is its format:

relation ? trueStatement : falseStatement;

The relation is any relational test such as age >= 21 or sales <= 25000.0. You also can combine the relational operators with the logical operators you learned about in Chapter 12, “How Do I Test Several Things at Once?” The trueStatement is any valid C statement, and the falseStatement is also any valid C statement. Here is an example of a conditional operator:

(total <= 3850.0) ? (total *= 1.10): (total *= 1.05);

Clue

image

The parentheses are not required, but they do help group the three parts of the conditional operator so that you can see them easier.

If the test in the first set of parentheses is true, the trueStatement executes. If the test in the first set of parentheses is false, the falseStatement executes. The conditional operator you just saw does exactly the same thing as this if-else statement:

image

This statement tells C to multiply total by 1.10 or by 1.05, depending on the result of the relational test.

Note

image

Just about any if-else statement can be rewritten as a conditional statement. The conditional requires less typing, you won’t accidentally leave off a brace somewhere, and the conditional runs more efficiently than an if-else because it compiles into more compact code.

Clue

image

The format of the conditional operator is obvious when you think of it like this: The question mark asks a question. Keeping this in mind, you could state the earlier example as follows: Is the total <= 3850.0? If so, do the first thing; otherwise, do the second.

Warning

image

C programmers don’t like the redundancy you saw in the earlier use of the conditional operator. As you can see, the total variable appears twice. Both times it is being assigned a value. When you face such a situation, take the assignment out of the conditional operator’s statements:

total *= (total <= 3850.0) ? (1.10): (1.05);

Don’t replace every single if-else with a conditional operator. Many times if-else is more readable, and some conditional statements are just too complex to squeeze easily into a conditional operator. However, when a simple if-else is all that’s needed, the conditional operator provides a nice alternative.

The conditional operator offers one additional advantage over if: The conditional often can appear in places where if can’t go. The following printf prints a trailing s if the number of pears is more than one:

printf("I ate %d pear%s", numPear, (numPear>1) ? ("s.") : ("."));

If the value in numPear is greater than 1, you’ll see something like this printed:

I ate 4 pears.

but if there is only one pear, you’ll see this:

I ate 1 pear.

Note

image

Maybe you’re wondering why the conditional operator is ?:, but the question mark and colon never appear next to each other. Well, that’s just the way it is. It would be too cumbersome to go around saying that the conditional operator looks like a question mark and a colon with some stuff in between.

The Small-Change Operators: ++ and --

Although the conditional operator works on three arguments, the increment and decrement operators work on only one. The increment operator adds 1 to a variable, and the decrement operator subtracts 1 from a variable. That’s it, ‘nuff said. Almost....

Incrementing and decrementing variables are things you would need to do if you were counting items (such as the number of customers who shopped in your store yesterday) or counting down (such as removing items from an inventory as people buy them). In Chapter 10, “What Else Can I Do with Expressions?,” you read how to increment and decrement variables using compound operators. Here, you will learn two operators that can more easily do the same. The increment operator is ++ and the decrement operator is --. If you want to add one to the variable count, here’s how you do it:

count++;

You also can do this:

++count;

The decrement operator does the same thing, only the 1 is subtracted from the variable. You can do this:

count--;

You also can do this:

--count;

As you can see, the operators can go on either side of the variable. If the operator is on the left, it’s called a prefix increment or prefix decrement operator. If the operator is on the right, it’s known as a postfix increment or postfix decrement operator.

Prefix and postfix operators produce identical results when used by themselves. It is only when you combine them with other expressions that a small “gotcha” appears. Consider the following code:

int i = 2, j = 5, n;
n = ++i * j;

The question is, what is n when the statements finish executing? It’s easy to see what’s in j because j doesn’t change and still holds 5. The ++ ensures that i is always incremented, so you know that i becomes 3. The trick is determining exactly when i increments. If i increments before the multiplication, n becomes 15, but if i increments after the multiplication, n be-comes 10.

The answer lies in the prefix and postfix placements. If the ++ or -- is prefix, C computes it before anything else on the line. If the ++ or -- is postfix, C computes it after everything else on the line finishes. Because the ++ in the preceding code is prefix, i increments to 3 before being multiplied by j. The following statement increments i after multiplying i by j and storing the answer in n:

n = i++ * j;  /* Puts 10 in n and 3 in i */

Being able to increment a variable in the same expression as you use the variable means less work on the programmer’s part. The preceding statement replaces the following two statements that you would have to write in other programming languages:

n = i * j  /*No comment*/
i = i + 1

Warning

image

The ++ and -- operators are extremely efficient. If you care about such things (most of us don’t), ++ and -- compile into only one machine language statement, whereas adding or subtracting 1 using +1 or -1 doesn’t always compile so efficiently.

Sizing Up the Situation

You use sizeof() to find the number of memory locations it takes to store values of any data type. Although most C compilers use 2 bytes to store integers, not all do. To find out for sure exactly how much memory is being used by integers and floating points, you can use sizeof(). The following statements do just that:

i = sizeof(int);    /* Puts size of integers into i */
f = sizeof(float);  /* Puts size of floats into f */

sizeof() works on variables as well as data types. If you need to know how much memory that variables and arrays take, you can apply the sizeof() operator to them. The following section of code shows you how:

image

Here is one possible output from this code:

The size of i is 2
The size of name is 12

Depending on your computer and C compiler, your output might differ because of the differences in integer sizes. Notice that the character array size is 12, which includes the null zero.

Clue

image

The length of a string and the size of a string are two different values. The length is the number of bytes up to but not including the null zero, and it is found via strlen(). The size of a string is the number of characters it takes to hold the string, including the null zero.

Rewards

image

• Use the conditional operator in place of simple if-else statements to improve efficiency.

• The conditional operator requires three arguments. Extra parentheses help clarify these three arguments by separating them from each other.

Use ++ and -- to increment and decrement variables instead of adding and subtracting 1 using assignment or the += and -= operators. ++ and -- are extremely efficient.

Pitfalls

image

• Don’t duplicate assignment statements on each side of the conditional operator’s :. Pull the variable and the assignment operator completely out of the conditional operator and place them on the left of the conditional to improve efficiency.

• Don’t think that prefix and postfix always produce the same values. Prefix and postfix are identical only when a single variable is involved. If you combine ++ or -- with other variables and expressions, the placement of prefix and postfix is critical to get the result you want.

In Review

The goal of this chapter was to round out your knowledge of C’s operators and show you most of the ones remaining to be learned. The longest C operator, ?:, and the shortest C operators, -- and ++, were taught. Understanding these operators doesn’t take a lot of work, yet the operators are powerful and substitute for complete statements in other languages. One of C’s operators doesn’t look like an operator at all. The sizeof() operator returns the number of memory locations consumed by whatever is in its parentheses.

Code Example

image

Code Analysis

The if statement is redundant. If you were to remove the if statement, the program would perform exactly the way it does with the if. The conditional operator does the same thing in one statement that the if does in four. The conditional operator assigns a gift of either $5 or $10, depending on the age of the user.

One is then added to the user’s age so that users can see their age a year from now (as if they couldn’t do this themselves!). Lastly, the code prints a message telling the user how much memory is taken up by integers on the machine running the program.

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

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