Operators
15.13 Summary of Operators and Precedence
The highest priority operators are listed first.
Operator Operation Evaluated.
() parentheses left to right [] square brackets left to right
++ increment right to left
-- decrement right to left
(type) cast operator right to left * the contents of right to left & the address of right to left - unary minus right to left ~ one’s complement right to left ! logical NOT right to left
* multiply left to right
/ divide left to right
% remainder (MOD) left to right
+ add left to right
- subtract left to right
>> shift right left to right << shift left left to right
> is greater than left to right >= greater than or equal to left to right <= less than or equal to left to right < less than left to right
== is equal to left to right != is not equal to left to right
& bitwise AND left to right ^ bitwise exclusive OR left to right | bitwise inclusive OR left to right && logical AND left to right || logical OR left to right
+= add assign right to left -= subtract assign right to left *= multiply assign right to left /= divide assign right to left %= remainder assign right to left >>= right shift assign right to left <<= left shift assign right to left &= AND assign right to left ^= exclusive OR assign right to left |= inclusive OR assign right to left
15.14 Questions
1. What is an operand?
2. Write a statement which prints out the remainder of 5 divided by 2. 3. Write a short statement which assigns the remainder of 5 divided by 2
to a variable called "rem".
4. Write a statement which subtracts -5 from 10.
5. Write in C: if 1 is not equal to 23, print out "Thank goodness for mathematics!"
Decisions 123
16 Decisions
Testing and Branching. Making conditions.
Suppose that a fictional traveller, some character in a book like this one, came to the end of a straight, unfinished road and waited there for the author to decide where the road would lead. The author might decide a number of things about this road and its traveller:
• The road will carry on in a straight line. If the traveller is thirsty he will stop for a drink before continuing.
• The road will fork and the traveller will have to decide whether to take the left branch or the right branch.
• The road might have a crossroads or a meeting point where many roads come together. Again the traveller has to decide which way to go. We are often faced with this dilemma: a situation in which a decision has to be made. Up to now the simple example programs in this book have not had any choice about the way in which they progressed. They have all followed narrow paths without any choice about which way they were going. This is a very limited way of expressing ideas though: the ability to make decisions and to choose different options is very useful in programming. For instance, one might want to implement the following ideas in different programs:
• If the user hits the jackpot, write some message to say so. "You’ve won the game!"
• If a bank balance is positive then print C for credit otherwise print D for debit.
• If the user has typed in one of five things then do something special for each special case, otherwise do something else.
These choices are actually just the same choices that the traveller had to make on his undecided path, thinly disguised. In the first case there is a simple choice: a do of don’t choice. The second case gives two choices: do thing 1 or thing 2. The final choice has several possibilities.
C offers four ways of making decisions like the ones above. They are listed here below. The method which is numbered 2b was encountered in connection with the C preprocessor; its purpose is very similar to 2a.
1: if (something_is_true) { /* do something */ } 2a: if (something_is_true) { /* do one thing */
} else { /* do something else */ } 2b: ? (something_is_true) : /* do one thing */ : /* do something else */ 3: switch (choice) {
case first_possibility : /* do something */ case second_possibility : /* do something */
.... }
16.1
if
The first form of the if statement is an all or nothing choice. if some condition is satisfied, do what is in the braces, otherwise just skip what is in the braces. Formally, this is written:
if (condition) statement; or if (condition) { compound statement }
Notice that, as well as a single statement, a whole block of statements can be written under the if statement. In fact, there is an unwritten rule of thumb in C that wherever a single statement will do, acompound statement will do instead. A compound statement is a block of single statements enclosed by curly braces.
A condition is usually some kind of comparison, like the ones discussed in the previous chapter. It must have a value which is either true or false (1 or 0) and it must be enclosed by the parentheses ( and ). If the condition has the value ‘true’ then the statement or compound statement following the condition will be carried out, otherwise it will be ignored. Some of the following examples help to show this:
int i;
printf ("Type in an integer");
scanf ("%ld",&i);
if (i == 0) {
printf ("The number was zero"); }
if (i > 0) {
printf ("The number was positive"); }
if (i < 0) {
printf ("The number was negative"); }
The same code could be written more briefly, but perhaps less consistently in the following way:
int i;
printf ("Type in an integer");
scanf ("%ld",&i);
if (i == 0) printf ("The number was zero"); if (i > 0) printf ("The number was positive"); if (i < 0) printf ("The number was negative");
The preference in this book is to include the block braces, even when they are not strictly required. This does no harm. It is no more or less efficient, but very often you will find that some extra statements have to go into those braces, so it is as well to include them from the start. It also has the appeal
Example Listings 127
that it makesifstatements look the same as all other block statements and it makes them stand out clearly in the program text. This rule of thumb is only dropped in very simple examples like:
if (i == 0) i++;
Theifstatement alone allows only a very limited kind of decision: it makes do or don’t decisions; it could not decide for the traveller whether to take the left fork or the right fork of his road, for instance, it could only tell him whether to get up and go at all. To do much more for programs it needs to be extended. This is the purpose of the elsestatement, described after some example listings..
16.2 Example Listings
/*****************************************/ /* */ /* If... #1 */ /* */ /*****************************************/ #include <stdio.h> #define TRUE 1 #define FALSE 0 /******************************************/ main () { int i; if (TRUE) {printf ("This is always printed"); }
if (FALSE) {
printf ("This is never printed"); } } /*******************************************/ /* */ /* If demo #2 */ /* */ /*******************************************/
/* On board car computer. Works out the */ /* number of kilometers to the litre */ /* that the car is doing at present */
#include <stdio.h> /*******************************************/ /* Level 0 */ /*******************************************/ main () { double fuel,distance; FindValues (&fuel,&distance); Report (fuel,distance); } /********************************************/ /* Level 1 */ /********************************************/
FindValues (fuel,distance) /* from car */
/* These values would be changing in */ /* a real car, independently of the */
/* program. */
double *fuel,*distance;
{
/* how much fuel used since last check on values */
printf ("Enter fuel used"); scanf ("%lf",fuel);
/* distance travelled since last check on values */
printf ("Enter distance travelled"); scanf ("%lf",distance);
}
/**********************************************/
Report (fuel,distance) /* on dashboard */
double fuel,distance;
{ double kpl;
if ... else 129
printf ("fuel consumption: %2.1lf",kpl); printf (" kilometers per litre\n");
if (kpl <= 1) {
printf ("Predict fuel leak or car"); printf (" needs a service\n"); }
if (distance > 500) {
printf ("Remember to check tyres\n"); }
if (fuel > 30) /* Tank holds 40 l */ {
printf ("Fuel getting low: %s left\n",40-fuel); }
}
16.3
if
...
else
The ‘if .. else’ statement has the form:
if (condition) statement1; else statement2;
This is most often written in the compound statement form:
if (condition) { statements } else { statements }
The ‘if..else’ statement is a two way branch: it means do one thing or the other. When it is executed, the condition is evaluated and if it has the value ‘true’ (i.e. not zero) then statement1 is executed. If the condition is ‘false’ (or zero) then statement2 is executed. The ‘if..else’ construction often saves an unnecessary test from having to be made. For instance:
int i;
scanf ("%ld",i);
if (i > 0) {
printf ("That number was positive!"); }
else {
printf ("That number was negative or zero!"); }
It is not necessary to test whether i was negative in the second block be- cause it was implied by the ‘if..else’ structure. That is, that block would not have been executed unless i were NOT greater than zero. The weary traveller above might make a decision such as:
if (rightleg > leftleg) { take_left_branch(); } else { take_right_branch(); }