Unary Operators

   


In contrast to binary operators, unary operators are only applied to one operand. The following sections look closer at the unary plus (+), the unary minus (-), the increment (++), and the decrement (--) operators.

Unary Plus and Unary Minus

The unary minus operator shown in the following


graphics/07infig13.gif

is not just a minus sign, as in the literals (like 18) we write on a piece of paper. It is an operator and will change the sign of the numerical expression to which it is applied. Consequently, if the variable height has the value 10, - height will return the value 10. If the value is 10, the result will be 10.

Note

graphics/common.gif

When the unary minus operator is applied to a variable, it does not change the value held by this variable, it merely changes the value returned from this variable.


Because unary minus is applicable to an operand, and an operand is defined in five different ways (see Syntax Box 7.1), it can be applied to the full range of numerical expressions. The following is a valid expression:


graphics/07infig14.gif

The unary operators shown in Table 7.1 have a higher precedence than any of the binary operators mentioned previously. An example illustrates why this makes sense:


graphics/07infig15.gif

-count is the first operation to take place that is intuitively how we understand a negation sign to work. If the unary minus operator had a lower precedence than any of the involved binary operators, the result would have been

 -(10 + 20 * 100) = -2010 

The unary plus (+) operator has no effect on the operand on which it is applied. For example, +10 is equal to 10 and +count is equal to count.

Syntax Box 7.4 Unary Plus and Minus Operators

 Unary_plus_expression ::=                + <Numerical_expression> Unary_minus_expression ::=                - <Numerical_expression> 

Increment and Decrement Operators

You have already learned about the increment operator (++) in Chapter 6, "Types Part I: The Simple Types." As you saw, it is a convenient operator when you want to increment a variable by one. If you declare a variable count as

 int count = 10; 

you can either add one to count by writing

 count = count + 1; 

resulting in count being equal to 11, or you can use the increment operator (++)

 ++count; 

Note

graphics/common.gif

The ++ symbol of the example presented here is positioned in front of, not after, the variable, as in previous examples. Both configurations increment the variable. However, they hold subtle differences discussed later. This is also true for the decrement operator (--) operator.


Similarly, you can deduct one from the value of count by applying the decrement operator (--):

 --count; 

Note

graphics/common.gif

The increment and decrement operators are not an essential part of the C# language. Any construct written in C# with these operators can be rewritten without them to perform exactly the same tasks. In fact, many languages do not include these operators as part of their operator repertoire.

They are inherited from C#'s predecessors C and C++ (this explains the ++ in C++). You will constantly bump into them because they are commonly used in the programming community.


The increment/decrement operator can be part of a longer arithmetic expressions.

The operation performed by the operator can then be divided into two sub-operations:

  • Increase the value of the variable it is applied to by one.

  • Return the value of the variable to which it is applied.

Line 12 of Listing 7.3 uses the increment operator as part of a longer expression.

Listing 7.3 Source Code for Library.cs
01: using System; 02: 03: class Library 04: { 05:     public static void Main() 06:     { 07:         int numProgrammingBooks = 2; 08:         int numStatisticsBooks = 1; 09:         int numActionBooks = 504; 10:         int totalBooks; 11: 12:         totalBooks = ++numActionBooks + numProgrammingBooks + 13:             numStatisticsBooks; 14:         Console.WriteLine("Number of action books: " + 15:             numActionBooks); 16:         Console.WriteLine("Total number of books: " + 17:             totalBooks); 18:     } 19: } Number of actions books: 505 Total number of books: 508 

Line 12 is an assignment statement. The increment operator is applied to the variable numActionBooks. When this statement is executed, the following actions will take place in the order they are displayed.

  1. numActionBooks is incremented by one.

  2. The new value of numActionBooks is returned and used in the rest of the expression to be added to numProgrammingBooks and numStatisticsBooks.

  3. The sum of the three variables is assigned to totalBooks.

The decrement operator works in exactly the same manner in an expression with the obvious difference of decrementing by one instead of incrementing by one.

Note

graphics/common.gif

Increment/decrement operators can only be applied to variables because the increment/decrement operators change the underlying value of a variable. Consequently,

 ++count 

has the same effect as

 count = count + 1; 

An assignment takes place when an increment/decrement operator is applied. It only makes sense to assign a value to a variable. For example, the following constitutes an illogical statement:


graphics/07infig16.gif

which makes us realize that

 ++20; 

is also unsound.


When the operator is positioned in front of the variable, it is called prefix form. When it is appended behind the variable, it is called postfix form. The difference between the two forms lies in the sequence of the two sub-operations performed by the operator.

Note

graphics/common.gif

The sequence of steps performed by the prefix form of the increment/decrement operators is reversed when in the postfix form.

Prefix form: (++count)

  1. Increase the value of the variable it is applied to by one.

  2. Return the value of the variable to which it is applied.

Postfix form: (count++)

  1. Return the value of the variable to which it is applied.

  2. Increase the value of the variable it is applied to by one.


You can see the difference between the two forms by changing line 12 of Listing 7.3 to


graphics/07infig17.gif

which results in the following output:


graphics/07infig17a.gif

The total number of books is not 508, as in the previous output, but 507, because the value of numActionBooks was not incremented until after its value had been used in the expression to calculate the total number of books.

Note

graphics/common.gif

According to Table 7.1, the precedence of the postfix increment/decrement operators is 1, whereas their prefix counterparts only have a precedence of 2. What is the significance of this difference? Consider the following extract from a previous line, but with all the whitespace removed:


graphics/07infig18.gif

How does the compiler evaluate this statement? It can either apply the postfix increment operator to numActionBooks (marked 1) or apply the prefix increment operator to numProgrammingBooks (marked 2). This is where the difference in precedence comes to the rescue; it removes the apparent ambiguity of the expression. Because of the higher precedence of the postfix increment, version 1 can be chosen without hesitation:

 (numActionBooks++) + numProgrammingBooks 

Precedence, in this context, is used to determine which variable the operator acts on and not when the increment/decrement operation takes place. We can still rely on the postfix increment/decrement operators to perform their increment/decrement operations after the other operations of the expression have taken place.


Tip

graphics/bulb.gif

Overuse of the increment/decrement operators as part of longer arithmetic expressions can severely obscure the readability of the source code. In fact, many professional programmers never use them in this way.

Their ability to be part of expressions is presented in this section so you can understand other programmer's source code.

Thus, instead of writing:

 12:       totalBooks = ++numActionBooks + numProgrammingBooks + 13:           numStatisticsBooks; 

as in Listing 7.3, it would be clearer first to make the increment of numActionBooks in a separate statement, and then let numActionBooks be part of calculating the total number of books:

 11:    ++numActionBooks; 12:        totalBooks = numActionBooks + numProgrammingBooks + 13:            numStatisticsBooks; 

When a statement only consists of a variable and an increment/decrement operator, such as in line 11, the prefix and the postfix version generate exactly the same results. Only when the variable appears as part of a longer expression do we see a difference between the two versions.

Increment and decrement operators are frequently used to increase or decrease the loop counters of a loop, as we shall see in the next chapter.


Syntax Box 7.5 The Increment and Decrement Operators

 Prefix_increment_expression ::=                  ++ <Variable_Identifier> Prefix_decrement_expression ::=                  --<Variable_Identifier> Postfix_increment_expression ::=                   <Variable_identifier>++ Postfix_decrement_expression ::=                   <Variable_identifier>-- 


   


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net