Está en la página 1de 28

Operators

Operators
Objectives
Understand the various categories of operators. Explore how relational operators and logical operators work together. Use short circuit evaluation. Use parentheses to change the order of precedence.

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

4-1

Operators

Operator Types
C# supports a number of operators, including: Relational operators (>, <, ==) Assignment (=) Mathematical (*,/,-,+) Logical (&&, ||, !)

When you looked at if statements (and many of the branching statements) you tested for certain conditions, such as whether two values were equal or one was greater than another. These are examples of relational operators. The assignment operator may be the operator used most in C#. You will often find yourself assigning the value of one object to another, or assigning to an object the value returned by a method. Mathematical operators are used less frequently, but many programs involve simple arithmetic, and nearly all C# programs use the increment operator (++) in loops. Logical operators are used when you are testing whether either or both of two (or more) conditions are true.

Relational Operators
The relational operators include: Equals (==) Not Equals (!=) Greater than (>) Greater than or equal to (>=) Less than (<) Less than or equal to (<=)
It is a common mistake to write the assignment operator, which is a single equal sign (=), when you mean to use the equals operator, which is a pair of equal signs with no space between them (==).

WARNING!

4-2

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Operator Types
Relational operators always evaluate to a Boolean (either true or false). Given two values and a relational operator, the entire expression is either true or it is not. For example:
7 < 5; 7 > 5; 5 > 5; 5 >= 5; // evaluates false // evaluates true // evaluates false // evaluates true

You will almost never compare two literal constants in this way; typically youll evaluate two variables or objects:
myAge < yourAge

And typically, youll do this evaluation within a test. Most often youll use an if statement or a while or for statement:
if ( myAge < yourAge ) // take some action while ( turnsLeft > 0 ) // take some action for ( i = 0; i < 10; i++ ) // take some action

In each of these cases, the evaluated expression will return true or false.

Mathematical Operators
The mathematical operators generally work the way youd expect. The addition operator (+) adds two values, the subtraction operator (-) returns the difference between two values. When you multiply two values (*) the expression evaluates to their product:
z = x * y; // assign to z the product of x and y

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

4-3

Operators

Division
There are no surprises with addition, subtraction, or multiplication. When you divide two int values, however, the result is what youd get in fourth grade: that is, the quotient is truncated! You will remember that back in fourth grade, the problem (13/5) had the answer 2, with a remainder of 3. That is, 5 went into 13 twice, with 3 left over. C# integer division works the same way. In the following expression, x has the value 2. The remainder is lost.
int x = 13 / 5;

When you divide doubles and floats, of course, you do get a decimal result, to the limits of the precision of the type.

Modulus
You can get at the remainder value in integer division, by using the modulus operator (%). Modulus returns only the remainder. The following expression evaluates to 3, because 13/5 is 2 with a remainder of 3, and % returns only the remainder:
int x = 13 % 5

It turns out that modulus is quite useful for finding every nth occurrence in a loop. See Operator.sln For example, to find every tenth occurrence in a loop, you might write something like the following:
for (int i = 11; i <= 100; i++) { Console.Write("{0} ",i); if (i % 10 == 0) Console.WriteLine("\t {0}", i); }

This code writes the values 11 through 100. After every ten values, it writes a tab and then writes the number followed by a new line. The result is shown in Figure 1.

4-4

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Operator Types

Figure 1. The modulus operator.

The first time through the loop, i has the value 11. The modulus operator returns the value 1 and the if statement fails:
if (i % 10 == 0)

11 % 10 is 1 because 11 / 10 is 1 with 1 left over. The second time through the loop i is 12, and 12 % 10 is 2, again the if fails, two is not equal to zero. This continues until i is 20. At that point the modulus operator returns 0 (20 % 10) which is equal to zero, and so the if statement is executed.

Concatenation
The addition operator (+) is also used to concatenate strings:
string s1 = hello; string s2 = world; string s3 = s1 + s2;

The result will be that s3 contains the string hello world. This has become such a common idiom in programming that few find it confusing. NOTE The space at the beginning of string s2 allows the concatenated string to be hello world rather than helloworld.

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

4-5

Operators

Self-Applied Operators
It is common to want to increment a variable or multiply a variable by a value, and then assign that value back to the variable itself. In C# you can, as you do in other languages, write the resulting value back to the variable:
myVariable = myVariable + 5;

If myVariable had the value 7 before this statement, it would now contain the value 12. Similarly, you can write:
int a = 5, b = 12; a = a * b;

After these two statements, variable a will have the value 60. This is such a common idiom, that C# provides a shorthand. The statement,
a = a * b;

is exactly equivalent to the statement,


a *= b;

The latter is just shorthand for multiply myself times b and reassign the value back to me. This shorthand can be applied to any of the mathematical operators:
a += b; a -= b; a *= b; a /= b; a %= b; // add b // subtract b // multiply by b // divide by b // modulus b

4-6

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Operator Types

Increment and Decrement


Adding or subtracting a single value to a variable is such a common occurrence that C# supports operators that do exactly that: the increment operator adds one to a value, and the decrement operator subtracts one. In addition, each of these comes in two flavors: prefix and postfix.

Prefix vs. Postfix Operator


The semantics of the prefix increment operator (++x) are increment and then fetch. The semantics of the postfix increment operator (x++) are fetch and then increment. You can see the difference by examining the following lines of code:
int a = 5, b = 7, c = 9, d = 11; a = ++b; // a = 8, b = 8 c = d++; // c = 11, d = 12

The first line initializes four int variables. The second line assigns to a the result of the prefix increment operator on b. The prefix operator increments b and then returns the value, and the incremented value is assigned to a. Since b started out as 7, the incremented value is 8, and both a and b now have the value of 8. The third line assigns to c the result of calling the postfix operator on d. The semantics here are to return the current value of d (11) and then to increment d. Thus, c has 11 and d has 12.

Logical Operators
C# supports three logical operators: && (Logical AND) evaluates true if both operand expressions are true. || (Logical OR) evaluates true if either operand expression is true. ! (Logical NOT) evaluates true if the operand expression is false.

One way to understand these operators is to examine their impact given a test case. If you assume that you have two integer variables, x and y, and that x has the value 5 and y has the value 12 then the following code will evaluate false, because while x does equal 5, y does not equal 7 and for the logical AND to evaluate true, both operands must be true.

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

4-7

Operators
(x == 5) && (y == 7)

On the other hand, the following expression does evaluate true, because even though y does not equal 7, x does equal 5 and logical OR evaluates true if either operand is true. You can read this as x is 5 or y is 7 and the answer to that is true.
(x==5) || (y == 7)

Finally, the following expression will evaluate true, precisely because x is not equal to 3. That is, the inner expression x == 3 evaluates false, and so the entire expression !(x==3) evaluates true. It is as if you said, It is false that x is equal to 3. That statement is true, it is false that x is 3.
!(x == 3)

Short Circuit Evaluation


The logical operators are typically used in tests, often in if statements, so you might see code like the following:
if ( (x == 3) && (y == 12) )

The body of the if statement will be executed only if the logical statement evaluates true, which in this case it will do only if x is equal to three and y is equal to 12. It turns out that the compiler may not need to evaluate the right side of a logical expression if the answer can be determined from the left side alone. For example, in a logical AND statement (&&) there is no need to evaluate the right side of the expression if the left side is false. Since they must both be true, if the left is false then the entire statement is false regardless of the value on the right. Similarly, in an OR statement, if the left statement is true, then it doesnt matter whether the right statement is true or not, the logical OR condition is satisfied if either side is true. You can test short circuit evaluation by creating a couple of methods that return Boolean values:

4-8

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Operator Types
static bool ReturnsTrue() { Console.WriteLine("In ReturnsTrue()."); return true; } static bool ReturnsFalse() { Console.WriteLine("In ReturnsFalse()."); return false; }

The first of these, returnsTrue always returns the value true, and the second, returnsFalse always returns false. You can now set up test conditions:
if (ReturnsTrue() || ReturnsFalse()) Console.WriteLine ("or statement worked!");

If you run this code, the call to ReturnsFalse will never be executed, as shown in Figure 2. The first half of the OR statement evaluates true, and so the OR condition is satisfied. There is no reason to call ReturnsFalse; it doesnt matter whether it returns true or false; the expression is already true, and the if statement executes.

Figure 2. Testing the OR with short circuit evaluation.

If you reverse the order of the test the second method must be tested:
//if (ReturnsTrue() || ReturnsFalse()) if (ReturnsFalse() || ReturnsTrue()) Console.WriteLine ("The || statement worked!");

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

4-9

Operators
The first method runs and returns false. Now the OR statement must execute the right side to see if it will return true. It does, so the OR statement is satisfied, as shown in Figure 3.

Figure 3. Reversing the test.

Similarly, you can set up an AND statement that will take advantage of shortcircuit evaluation:
if (ReturnsFalse() && ReturnsTrue()) Console.WriteLine ("The && statement worked!"); else Console.WriteLine("Nope, the && statement failed.");

In this case, once the first method call, ReturnsFalse returns a value of false, there is no point in checking the second method call. Whether or not it returns true, the entire if statement has already failed its test, because the AND statement must evaluate true for both operands. The result is that the else clause is invoked, as shown in Figure 4.

Figure 4. Short circuit evaluation of the AND statement.

4-10

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Operator Types

Try It Out!
See operators.sln To get a good handle on operators, youll create a simple console application.

1. Open a new console application, and name it Operators. 2. Set up a series of variables.
int intA, intB; float floatA, floatB; intA = 12; intB= 7; floatA = 12; floatB= 7;

3. You are now ready to explore the arithmetic operators for addition, subtraction, multiplication, and division.
Console.WriteLine("Arithmetic operators...");

Console.WriteLine("intA + intB: {0}", intA + intB); Console.WriteLine("intA - intB: {0}", intA-intB); Console.WriteLine("intA * intB: {0}", intA * intB); Console.WriteLine("intA / intB: {0}", intA / intB); Console.WriteLine("intA % intB: {0}", intA % intB);

Console.WriteLine( "\nfloatA + floatB: {0}", floatA + floatB); Console.WriteLine( "floatA - floatB: {0}", floatA-floatB); Console.WriteLine( "floatA * floatB: {0}", floatA * floatB); Console.WriteLine( "floatA / floatB: {0}", floatA / floatB); Console.WriteLine( "floatA % floatB: {0}", floatA % floatB);

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

4-11

Operators
4. Compile and run the program. The results are shown in Figure 5, but there are a few things to note. The console output for the first float variable begins with \n:
Console.WriteLine( "\nfloatA + floatB: {0}", floatA + floatB);

The \n character sequence is an escape sequence that represents a new line character. That is why there is an extra vertical space between the int examples and the float examples. Note also that the output is identical for addition, subtraction, and multiplication, but the int example uses integer division (with truncation), and the float shows the decimal value.

Figure 5. The arithmetic operators.

5. Add the following code to the program:

4-12

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Operator Types
int x = 5; int z = 0;

Console.WriteLine("\n\nx: {0}", x); z = ++x; Console.WriteLine("int z = ++x; x: {0}, z: {1}", x, z);

Console.WriteLine("\n\nx: {0}", x); z = x++; Console.WriteLine("z = x++; x: {0}, z: {1}", x, z);

Console.WriteLine("\n\nx: {0}", x); z = x--; Console.WriteLine("z = x--; x: {0}, z: {1}", x, z);

Here you create two integer variables, x and z, initializing x to 5 and z to 0. You then apply the prefix increment operator to x and assign the value to z, displaying the result. You then apply the postfix increment operator and finally the postfix decrement operator. 6. To simplify the output, comment out the earlier code, and run the program. The results are shown in Figure 6. You can see the differing impact of prefix and postfix. In the first example, x is incremented before its value is fetched, so both x and z have the incremented value of 6.

Figure 6. Increment and decrement.

In the second example, the value of x (6) is fetched and assigned to z, and then x is incremented to 7. C# Professional Skills Development
Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

4-13

Operators
In the third example, the value in x (7) is assigned to z, and then x is decremented to 6. 7. Return to the code and comment out what you have so far, adding the following:
int testValue = 7;

if (testValue == 6) Console.WriteLine("testValue is 6!");

if (testValue != 6) Console.WriteLine("testValue is not 6!");

if (testValue > 6) Console.WriteLine("testValue is greater than 6");

if (testValue >= 6) Console.WriteLine( "testValue is equal to or greater than 6");

8. Compile and run this test code to see the impact of the relational operators. The results are shown in Figure 7.

Figure 7. Relational operators.

The program begins by initializing x to the value 7. The first test fails because testValue is not equal to 6 and so nothing is printed:
if (testValue == 6) Console.WriteLine("testValue is 6!");

4-14

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Operator Types
The second test succeeds, and the message is printed:
if (testValue != 6) Console.WriteLine("testValue is not 6!");

The final two tests succeed as well; the value 7 is both greater than 6 and also greater than or equal to 6.

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

4-15

Operators

Operator Precedence
Operators are evaluated in a very strict order as established by the rules of precedence. You may remember some of these rules from high school algebra. For example, multiplication has a higher precedence than addition:
nt x = 8 + 5 * 3;

After this statement executes, x will have the value 23 rather than 39, because the order of operations is 5*3 (15) plus 8 (23), rather than 8+5 (13) times 3 (39). Every operator has its own precedence level, and operators with higher precedence levels are invoked first.

Using Parentheses
You can change the order of precedence by using parentheses. For example:
int x = (8 + 5) * 3;

In this example, x evaluates to 39. The parentheses are evaluated first, and the operation is 8 + 5 (13) times 3 or 39. Using parentheses makes your program easier to read and maintain. You may want to use parentheses even when they dont change the order of operations, if only to document your intent.

4-16

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Preprocessor

Preprocessor
Preprocessor directives are not, strictly speaking, operators, but they act as special instructions to the C# compiler and precompiler. The preprocessor is an operation that runs before your program is compiled. Preprocessor directives allow you to provide special instructions to the compiler, which is useful when you want to control what portions of your program are compiled. Preprocessor directives begin with the character #. This must be the very first character on the line, and there must be no space between the # and the directive name. For example, the directive might be:
#define

The #define directive defines an identifier within the preprocessor. You can then test whether that identifier has been defined using #if and #endif. If the test succeeds, the code within the if/endif block will be compiled; otherwise it will not be compiled and will not be in the executable code.
#define Debug #if Debug // compile the code here // only if debug is defined #endif

You can also add an else clause to the if statement:


#define Debug #if Debug // compile the code here // only if debug is defined #else // compile this code only if // debug is NOT defined #endif

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

4-17

Operators
Finally, you can add elif clauses to create complex switch-like statements:
#define Debug #if Debug // compile the code here // only if debug is defined #elif Test // compile if debug is not defined // but test is #else // compile this code only if // debug and test are both NOT defined #endif

Typically, preprocessor directives are used when you want to mark a section of code to be compiled only if an identifer exists. Note that the identifier does not have to have a specific value, it just has to be defined. You might use preprocessor directives when you want to mark out an area of code to be compiled only when debugging. You might also use it for compiling different versions for different customers or platforms.

4-18

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Preprocessor

Summary
C# supports a wide variety of operators, including relational, mathematical, and logical operators. The mathematical operators act as you might expect, except that integers perform integer division, truncating the result. You can find the remainder in integer division by using the modulus (%) operator. You can concatenate two strings using the addition operator (+). C# provides both a prefix and a postfix increment (and decrement) operator. The semantics of prefix are increment and then fetch, while the semantics of post fix are fetch and then increment. The Logical operators && and || can be short circuited. All operators have precedence, but the order of evaluation can be overridden by using parentheses.

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

4-19

Operators

(Review questions and answers on the following pages.)

4-20

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Preprocessor

Questions
1. What is a practical use for the modulus operator? 2. What is the difference between integer multiplication and multiplication with floats? 3. What is the difference between using the prefix increment operator vs. the postfix increment operator? 4. How can you change the order in which operators are evaluated? 5. What is the code to test if DEBUG has been defined for the preprocessor?

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

4-21

Operators

Answers
1. What is a practical use for the modulus operator?
The modulus operator may be used during loops to find intervals. When you modulus a number with an exact multiple the result is 0. You can test for that condition to take action every nth iteration.

2. What is the difference between integer multiplication and multiplication with floats?
None, it was a trick question. Multiplication, addition, and subtraction are identical; integer division however, is quite different from division with floats.

3. What is the difference between using the prefix increment operator vs. the postfix increment operator?
The prefix operator increments the value before it is assigned, while the postfix operator assigns the original value and then increments.

4. How can you change the order in which operators are evaluated?
Use parentheses. Parentheses have the highest precedence and are evaluated first.

5. What is the code to test if DEBUG has been defined for the preprocessor?
#if Debug //code here #endif

4-22

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Preprocessor

Lab 4: Operators

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

4-23

Lab 4: Operators

Lab 4 Overview
In this lab youll learn how to use operators in your program To complete this lab, youll need to work through two exercises: Using Mathematical Operators Comparing Values with the Comparison Operators

Each exercise includes an Objective section that describes the purpose of the exercise. You are encouraged to try to complete the exercise from the information given in the Objective section. If you require more information to complete the exercise, the Objective section is followed by detailed step-bystep instructions.

4-24

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Using Mathematical Operators

Using Mathematical Operators


Objective
In this exercise, youll use mathematical operators to manipulate values.

Things to Consider
What is the difference between division with integers and floats? What does modulus do with integers and floats?

Step-by-Step Instructions
1. Open the project named Operators.sln in the Operators folder. This project has been prepared for you. 2. Fill in the values for the WriteLine statements. For example, the value you might fill in for the first WriteLine would be:
Console.WriteLine("firstInt + secondInt: {0}", firstInt + secondInt);

3. Fill in the operator in the if statement, replacing the question mark. Your goal is to have the if statement execute every fifth value. 4. Compile and run the program.

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

4-25

Lab 4: Operators

Comparing Values with the Comparison Operators


Objective
In this exercise, youll work with the comparison operators.

Things to Consider
What is the difference between > and >=?

Step-by-Step Instructions
1. Open the program named Comparison Operators.sln in the Comparison Operators folder. 2. This project has been created for you, but you must fill in the missing operators. Replace the question marks with the appropriate operators. For example, you might replace the first question mark with the equals (==) operator:
if (comparisonValue ? 6) Console.WriteLine("comparisonValue is 6!");

3. Be sure to add the decrement operator where the comment shows.


comparisonValue?; // decrement the comparison value

4. Compile and run the program, as shown in Figure 8.

4-26

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

Comparing Values with the Comparison Operators

Figure 8. Running the comparison program.

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

4-27

Lab 4: Operators

4-28

C# Professional Skills Development


Copyright by Application Developers Training Company and AppDev Products Company, LLC All rights reserved. Reproduction is strictly prohibited.

También podría gustarte