What are operators in programming

Chapter 3: Operators

Programming in C ++: Introduction



This book is licensed under a Creative Commons license.


3.1 Processing data in variables

After information storage, the information processing

In the last chapter you learned a lot about variables and now you know a lot about variables. They know that there are different types of data - both intrinsic and non-intrinsic. They know how to create variables, store values ​​in them and exchange values ​​between variables. You have seen that letters are stored as numbers and that the assignment of numbers to letters and other characters takes place in code tables. And last but not least, you've even learned about arrays. You now know that storing information in programs is a simple matter of using variables.

However, information storage alone is not enough. Computer programs don't just store data, they process it. And this is exactly where the operators come into play: With them it is possible to access variables and process information that is stored in variables.

int i; i = 3;

Take a closer look at the above example from the previous chapter. You know that a data type is the name of a variable, that statements in C ++ are known to end with a semicolon - but what is this equal sign?

The equal sign is one of the many operators in C ++. This is the assignment operator. Without this operator it would not be possible to save values ​​in variables. You have often used the assignment operator and used it to store numbers or letters in variables. This is also the actual function of the assignment operator: values ​​that are specified directly by the programmer or that are stored in other variables are transferred to a variable and stored there - i.e. to assign the value.

In addition to the assignment operator, there are a number of operators in C ++. Some of them are self-explanatory, others are probably completely incomprehensible to you at the moment, because you cannot yet imagine any area of ​​application. Experience has therefore shown that this chapter is a rather simple chapter. Much will immediately make sense to you, others will be too technical and insignificant at the moment. Nevertheless, in this chapter you should get an overview of all operators that are available in C ++, because in the end there are not too many and you have therefore seen all operators at least once.

The most important thing is not that you know every operator by heart, but that by the end of the chapter you have understood what the purpose of operators is and how they are basically used.


3.2 Arithmetic operators

The four basic arithmetic operations

Arithmetic operators are,,, and. They are used for the basic arithmetic operations known from mathematics. As is known from mathematics, these are exclusively binary operators. Binary operators are operators that each require exactly two values ​​or variables. There must be a value or a variable on both sides of binary operators - otherwise the compiler reports an error.

The arithmetic operators enable the four basic arithmetic operations to be carried out: Values ​​or variables can be added with, subtracted with, multiplied with and divided with. The operator is the modulo operator: It performs just like a division, but returns the integer remainder of the division as the result.

int a, b, c; a = 6; b = 4; c = a + b; c = a - b; c = a * b; c = a / b; c = a% b;

The above lines of code demonstrate the use of arithmetic operators: There is a variable on both sides - that is, to the right and left of the operators. Also note that when information is processed with the help of operators, the assignment operator is almost always on the same line. Otherwise, for example, an addition would be carried out, but the result of the addition would not be saved at all. The C ++ compiler wouldn't complain here because it is valid C ++ code - only you don't get much of an addition if you don't save the result anywhere.

While the operators and work as usual in mathematics, and must be discussed in more detail. In the example above,, and are variables of the type. If two variables of the type are divided and the result is saved in a variable of the type, the fractional part is lost. So while dividing 6 and 4 actually results in 1.5, only the number 1 is stored in. There is also no rounding up or down - the fractional part is simply lost because it cannot be stored in a variable of the type.

What happens in the modulo operation? The program divides 6 and 4. The integer result is 1, leaving a remainder of 2. The remainder is returned by the modulo operation, so that variable 2 is stored.


3.3 Logical operators

Linking truth values

Logical operators make it possible to link truth values. The logical operators and are binary operators, the logical operator is a unary operator. Unary operators expect only one operand, while binary operators expect two operands.

bool b1, b2, r; b1 = true; b2 = false; r = b1 && b2; r = b1 || b2; r =! b1;

The operator is the logical AND. This operator returns the truth value as the result if exactly both operands are. If there is only one of the two operands, the logical AND returns as the result.

That is the logical OR. The logical OR returns the truth value as the result if at least one of the two operands is. If both operands are used, the logical OR returns as the result.

The unary logical operator returns when the operand is and returns when the operand is. This operator is called the NOT operator. It simply reverses the truth value of the operand.

As with the arithmetic operators, the result must also be saved explicitly with the logical operators if it is not to be lost. The last line in the above example, in which the logical operator is used, returns the truth value as the result. After this line, however, the variable is still set to - the value of the variable does not change!


3.4 Bitwise operators

Set, delete and move bits

The bitwise operators,,,, and allow bits to be set, cleared, and shifted. In the book General basics of programming the meaning of,, and is discussed in detail. These are the bitwise AND, OR, NOT and EXCLUSIVE OR operators. The bitwise operators are not presented in detail in this book, as they are only required for very specific operations to process bits that are not essential for learning the C ++ programming language.

If the operators and from the previous example programs sound familiar to you: You have actually worked with these operators and "pushed" variables into the standard output. You will learn in this chapter why the bitwise operators in connection with do not shift bits but display information on the screen - that is, have a completely different meaning.


3.5 Comparison operators

Compare values ​​and variables

As the name suggests, comparison operators enable values ​​and variables to be compared. You can use the,,,, and operators to check for equality, inequality, greater than or less than, or greater than or equal to or less than or equal to. All comparison operators are binary operators.

Comparison operators return a truth value as the result - either or. The result depends on whether the comparison is correct or not.

int a, b; bool r; a = 5; b = 10; r = a == b; r = a! = b; r = a> b; r = a = b; r = a <= b;

Relational operators are mainly required in control structures when code has to be executed or not depending on certain conditions. You will get to know control structures in the following chapter.

Be sure to write for an assignment but write for an equality check. Especially beginners in the programming languages ​​C and C ++ often find that they want to check for equality, but forget the second equal sign and therefore write an assignment.


3.6 Combined assignment operators

Programmers are lazy people

Combined assignment operators are assignment operators that are combined with other operators. The meaning and purpose is ultimately an abbreviated notation for shorter, clearer code.

int a, b; a = 5; b = 10; a = a + b;

What is happening in the above program? The variables and are added using the arithmetic operator, whereupon the sum is stored in the variable using the assignment operator. This can also be written as follows with a combined assignment operator.

int a, b; a = 5; b = 10; a + = b;

Pay attention to the last line of code. This line does the same calculation as in the previous example: it is added to and the result is stored in.

Just as a combined assignment operator can be formed using the arithmetic operator, the following combined assignment operators can be formed using other operators:,,,,,,, and.


3.7 Increment and decrement operators

Programmers are really lazy

Take a look at the following code.

int a, b; a = 5; b = 1; a + = b;

In this case the variable is increased by the value 1; one could also say incremented. The special increment operator is used to increase variables only by the value 1. This is a unary operator. So the following code does the same as the code above.

int a; a = 5; ++ a;

Just as there is an increment operator, there is also a decrement operator. With the value of a variable is decreased by 1.

Increment and decrement operators can also be specified after a variable. Whether they are in front of or behind a variable can be decisive. Consider the following example.

int a, b; a = 5; b = ++ a; b = a ++;

After the above example code has run to the end, the value 6 is stored in the variable and the value 7 in the variable. What happened? If the increment operator is in front of the variable, the variable is increased and the value increased by 1 is returned. If the increment operator is behind the variable, the variable is increased, but the previous value not yet increased by 1 is returned. In both cases, the variable is assigned the value 6 in the example above.

What applies to the increment operator, of course, also applies to the decrement operator. Here, too, it can be decisive whether the operator is specified before or after the variable.

If it is irrelevant for the program logic whether you put the operator in front of or behind the variable, then put it in front of it - the operator may work faster than if it is behind the variable.


3.8 Precedence Table

Order of operator execution

Consider the following code and guess what result will be stored in the variable r.

int a, b, c, r; a = 2; b = 3; c = 4; r = a + b * c;

Does C ++ store the value 20 or 14 in the variable? C ++ adheres to the dot-before-line rule and calculates the value 14 for the variable, but what does the following example look like?

bool a, b, c, r; a = false; b = true; c = true; r = a && b! = c;

Three variables of the type are linked via the logical operator and the comparison operator. What kind of value is now saved in the variable?

The order in which operators are executed is determined by the precedence table in each programming language. This indicates which priority each operator has. The higher the priority, the sooner the operator is executed. Just because the operator has a higher priority than the operator does the first example actually result in 14. If the priorities were defined differently, they could be executed first and then instead - no problem at all for a programming language. The order of execution is simply defined and that's it.

descriptionOperator symbolpriorityEvaluation order
Brackets () [] 14 Left to right
Component selection . -> 14 Left to right
Arithmetic negation - 13 From right to left
Logical negation ! 13 From right to left
Bit logic negation ~ 13 From right to left
Increment ++ 13 From right to left
Decrement -- 13 From right to left
Arithmetic operators * / % 12 Left to right
+ - 11 Left to right
Shift operators << >> 10 Left to right
Comparison operators > >= < <= 9 Left to right
== != 8 Left to right
Bit operators & 7 Left to right
^ 6 Left to right
| 5 Left to right
Logical operators && 4 Left to right
|| 3 Left to right
Assignment operators = += -= *= /= %= >>= <<= &= ^= |= 2 From right to left
Sequence operator , 1 From right to left

Using this table, you can now also see whether the operator or the operator is executed first - it is the comparison operator. Therefore, in the previous example, the result is saved in the variable.

We haven't even got to know the two operators with the highest priority. Consider the following modified example.

int a, b, c, r; a = 2; b = 3; c = 4; r = (a + b) * c;

Now the addition is carried out first and then the multiplication. That is, the result now gets 20. The brackets are also an operator, namely the operator with the highest priority. This means that we can change the evaluation order of operators at any time by using parentheses. Use parentheses even if you are not sure whether the operators you are using will actually be executed in the order you want them to be. The brackets don't hurt, but they enforce the exact order of execution that you would like.

We ignore the two operators listed in the precedence table as component selections. These operators are also known as access operators. The access operator is required in connection with pointers and objects. The access operator will occupy us when we learn about structures in a later chapter.

If there are several operators with the same priority one behind the other, the order of evaluation takes place one after the other - either from left to right or from right to left. Here, too, only a look at the precedence table will help. As a rule of thumb, binary operators are executed from left to right, unary operators from right to left.


3.9 Context dependency

Plus is not always plus

The meaning of an operator depends crucially on the type of its operands. You were already made aware of this peculiarity when the bitwise operator was briefly introduced. As described in this chapter, it shifts bits. In the example programs that you have seen so far, however, it has a completely different function: There it outputs data to the standard output.

#include int main () {int i = 2; std :: cout << (i << 2) << std :: endl; }

In the example program above, the operator is used in two different situations. In the round brackets it shifts bits in the variable, two places to the left. Outside the round brackets, it outputs data to the standard output.

The meaning of the operator depends on the type of its operands. Since a variable of the type is processed in the brackets, it follows its original meaning and shifts bits. Outside the brackets, however, it is used in conjunction with. And is based on a data type for which the operator has been given a new meaning.

The operators presented in this chapter have a standard function for intrinsic data types. You have got to know them in this chapter. However, if you use the operators in connection with non-intrinsic data types, the operators have a completely different meaning or may not be applicable at all. The meaning of operators in connection with non-intrinsic data types depends entirely on the definition of the non-intrinsic data types. When you later create your own data types, you will see how you program functions for operators for your own data types. This is in the book Programming in C ++: structure presented in detail.

The data type it is based on is programmed to accept and work with an operator. The way the operator works is that the operand to the right of the operator is taken and passed on to the standard output. Although the operator looks identical to the bitwise operator, it has a completely different function.Defining functions for operators related to non-intrinsic data types is one of the strengths of C ++ - a language property not available to C or Java programmers.

Take a look at the following sample program to get an impression of the advantages of adapting operators for non-intrinsic data types.

#include #include int main () {std :: string a, b, c; a = "Hello,"; b = "world"; c = a + b; std :: cout << c << std :: endl; }

Here two variables and, both with a non-intrinsic data type, are linked with one. This, as you have learned in this chapter, adds numbers. However, since there are no numbers to the left and right of the, but variables of the type, the question arises what the meaning of is in this context. Do you have any ideas?

The plus operator has been defined for type variables in such a way that character strings can be linked and attached to one another. The above example program outputs to the screen. The advantage of redefining for variables of type is that the code becomes easier to read and understand. The fact that this leads to a combination of character strings in this context is obvious to most programmers and helps to increase the readability of the code.

Incidentally, changing the way operators work in connection with intrinsic data types is not possible in C ++. So if you use the operator to link two variables of the type, an addition is always carried out automatically, as presented in this chapter. There is no exception.


3.10 Exercises

Practice creates masters

You can purchase the solutions to all of the exercises in this book as a ZIP file.

  1. Develop a C ++ application that prompts the user for three numbers. Let the program add 10 to the first number entered, multiply the result by the second number entered, and then divide by the third number entered. The calculation should be done within a single line of code. The result should be displayed on the screen.

  2. Develop a C ++ application that prompts the user for a four-digit number. The program should then calculate the cross sum of the four-digit number and display the result on the screen.


Copyright © 2001-2010 Boris Schäling