Файл: Programming Microcontrollers in C, 2-nd edit (Ted Van Sickle, 2001).pdf
ВУЗ: Не указан
Категория: Не указан
Дисциплина: Не указана
Добавлен: 15.06.2025
Просмотров: 4078
Скачиваний: 1
30 Chapter 1 Introduction to C
When this mask is ANDed with r, all of the bits of r, with the exception of the least significant three bits, will be ANDed with a 1, and these bit values will remain unchanged. The least significant three bits will be ANDed with 0 and the result in these three bits will be 0. The bitwise OR will turn bits on. Suppose you wanted to turn bits 2 and 3 of r above on. Here you would use
r = r | 0x0c;
The hexadecimal number 0x0c is a number that has bits 2 and 3 turned on and all other bits turned off. This OR operation will leave bits 2 and 3 on and all other bits will remain unchanged. Suppose that you want to complement a bit in a variable. For example, bit 0 of the memory location PORTA must be toggled each time a certain routine is entered. The expression
PORTA = PORTA ^ 1;
will perform this operation. All of the bits except for bit 1 of PORTA will remain unchanged because the exclusive OR of any bit with a 0 will not change the bit value. However, if bit 1 is 1 in PORTA the exclusive OR will force this bit to 0. If this bit is 0, the exclusive OR will force this bit to a 1. Therefore, the above expression will comple ment bit 0 of PORTA each time it is executed.
The bitwise operators &, |, and ^ are of lower precedence than the equality operators, and higher precedence than the logical AND operator. The bit shift operators are of the same precedence, of lower precedence than the arithmetic operators + and - , and of higher precedence than the relational operators.
Increment and Decrement Operators
When the C language was written, every effort was made to write a language that is concise and yet unambiguous. Several powerful short-hand operators were included in the language that will shorten the program. The increment and decrement operators are examples of such short-hand operators. In the examples earlier there were in stances of expressions such as
i = i + 1;
Increment and Decrement Operators |
31 |
Here the i value stored in memory is replaced by one more than the value found there at the beginning of execution of the expression. The C expression
++i;
will do exactly the same thing. The increment operator ++ causes 1 to be added to the value in the memory location i. The decrement operator -- causes 1 to be subtracted from the value in the memory location. The increment and decrement operators can be either pre fix or postfix operators. If, like above, the ++ operator precedes the variable, it is called a prefix operator. If the variable is used in an expression, it will be incremented prior to its use. For example, sup pose i = 5. Then the expression
j = 2 * ++i;
will leave a 12 for the value j and 6 for i. On the other hand, if i again is 5, the expression
j = 2 * i--;
will leave a value of 10 for j and 4 for I.
An easy way to see how the preincrement and the postincrement works is as follows: Suppose that you have a pair of statements
j=j+1;
<statement with j>
These statements can be replaced with
<statement with ++j>
The preincrement means that you should replace j with j+1 before you evaluate the expression. Likewise the statements
<statement with j> j=j+1;
can be replaced with
<statement with j++>
with the post increment, you should evaluate the expression and then replace j with j+1.
32 Chapter 1 Introduction to C
Often somebody will wonder what will happen if you have mul tiple increments, either pre or post, of a variable within a single expression. There is an easy answer for that question. Do not do it. The standard provides that between sequence points, an object shall have its value modified at most once and the prior value of the object shall be accessed only to determine its value. Interpretations of the above requirements disallow statements such as
j = j++;
or
a[j] = j++;
or
m = j++ + ++j;
Assignment Operators
Another shorthand that was included in C is called the assign ment operator. When you are programming, you will find that expressions such as
i = i+2;
or
x = x<<1;
are used often. Almost any binary operator can be found on the right side of the expression. A special set of operators was created in C to simplify these expressions. The first expression can be written
i += 2;
and the second
x <<= 1;
These expressions use what is defined as an assignment operator. The operators that can be used in assignment operators are
+ |
>> |
- |
<< |
*&
Increment and Decrement Operators |
33 |
/^
%|
If you have two expressions e1 and e2, and let the operand $ repre sent any binary C operator, then
e1 $= e2;
is equivalent to
e1 = (e1) $ (e2);
The precedence of all of the operator assignments are the same and less than the precedence of the conditional operator discussed in the next section. These operators assignments and the = operator are associated from right to left.
The Conditional Expression
Another code sequence found frequently is
if(exp1) exp2 ;
else exp3 ;
The logical expression exp1 is evaluated. If that expression is TRUE, exp2 is executed. Otherwise, exp3 is executed. In the compact no tation of C, the above code sequence can be written
exp1 ? exp2 : exp3;
This expression is read if exp1 is TRUE, execute exp2. Otherwise, execute exp3. Another way of stating this is that if exp1 is TRUE, the value of the expression is exp2; otherwise the value of the ex pression is exp3.
The conditional expression is found often in macro definitions, which we’ll discuss later.
EXERCISES
1.Write a program to determine if a number is even or odd.
2.Write a function that determines the number of bits in an integer on your machine.
34Chapter 1 Introduction to C
3.Write a program that will rotate the bits in the number 0x5aa5 to the left by n bits. A rotate differs from a shift in that the most significant bit will be shifted into the least significant bit during the rotation. A shift merely shifts zeros into the least significant bit.
4.An arithmetic right shift propagates the most significant bit to the right when the number is shifted right. If zeros are shifted into the most significant bit, the shift is called a logical right shift. Write a program that determines whether your compiler implements a logi cal or arithmetic right shift with the operator >> with both signed and unsigned arithmetic.
5.Write a function upper(c) that returns the upper case letter if the character c is a lower case letter. Otherwise it shall return the char acter c.
6.If you used the if() else construct in problem 4, rewrite the func tion to use the conditional expression.
Precedence and Associativity
Here is a summary of the rules of both precedence and associa tion of all C operators. The higher an operator falls in the table, the higher its precedence. Operators that fall on the same line are all of the same precedence. All symbols used in C are operators. There fore, the operator () refers to the parentheses enclosing the arguments to a function call. The operator [] refers to the brackets enclosing the argument of an array. The period operator . and the comma operator , will both be discussed when introduced. Likewise, the -> and the sizeof operators will be introduced later.
Operator |
Associativity |
|
() |
[] -> . |
left to right |
! ~ ++ — + - * & (type) sizeof |
right to left |
|
* / % |
left to right |
|
+ |
- |
left to right |
<< |
>> |
left to right |
Precedence and Associativity |
35 |
|
< <= > => |
left to right |
|
== != |
left to right |
|
& |
left to right |
|
^ |
left to right |
|
| |
left to right |
|
&& |
left to right |
|
|| |
left to right |
|
?: |
right to left |
|
= += -= *= /= %= &= ^= |= <<= >>= right to left |
||
, |
left to right |
|
Note the very high precedence of the parentheses and the square brackets. It is the high precedence of these operators that allows the programmer to force operations that are not in line with the normal precedence of the language. The second highest precedence is the list of unary operators. These operators are all associated from right to left.
EXERCISES
1.Which of the following words are valid names for use in a C pro gram?
able |
toots |
What_day_is_it |
WindowBar |
_calloc |
8arnold |
Hurting? |
value |
constant |
Constant |
sizeof |
continue |
2.Write a program to evaluate the constant
( 1.0377x107 + 3.1822x103 ) / ( 7.221x104 + 22.1x106 ) The answer will be 0.468162.
3.Write a function that raises the integer x to the power n. Name the function x_to_the_n, and write a program that evaluates x_to_the_n for several different values of both x and n.
36Chapter 1 Introduction to C
4.Write a program that will examine a specified year and determine if it is a leap year.
5.Write a program that will count the number of digits in an input file. Record and print out the number of occurrences of each digit.
6.In C the term “white space” refers to the occurrence of a space, a tab character, or a new line character. Write a program that will evaluate the number of white space characters in an input file.
Program Flow and Control
Program flow and control comprise several different means to control the execution of a program. Looping constructs, for example, control the repeated execution of a program segment while adjusting parameters used in the execution at either the beginning or the end of the loop. Two way branches are created by if/else statements, and the choice of one of many operations can be accomplished with the else if or switch/case statements. The following para graphs will provide a quick look at each of these program flow and control methods.
The While Statement
There are three looping constructs available to the C programmer: the while() statement, the for(;;) statement and the do/ while() statement. The following program demonstrates the use of the while looping construct along with some other concepts. We have seen the while statement earlier, but the following program will pro vide a new look at its use.
#include <stdio.h>
int main(void)
{
int guess,i;
i=1; guess = 5;
while(guess != i)
{
Program Flow and Control |
37 |
i = guess;
guess = (i + (10000/i))/2;
}
printf(“The square root of 10000 is %d\n”,guess);
return 0;
}
As in the first example, the #include statement is used to bring standard input/output features into the program, and the program starts with the function definition main(). Inside of the main pro gram, the first statement is
int guess,i;
This statement defines the variables guess and i as integers. No value is assigned to i at this time, but a space in memory is allocated to guess and i and the space is sufficient to store an integer. The first executable statement in the program is
i=1;
This statement is called an assignment statement. The equal sign here is a misnomer. The statement is read “replace the contents of the memory location assigned to i with a 1.’’ The next statement
guess = 5;
assigns a value 5 to the variable guess. The statement
while(guess != i)
invokes a looping operation. The while operation will cause the statement following to execute repeatedly. At the beginning of each loop execution, the while argument guess!=i is checked. This argument is read “guess is not equal to i.” So long as this argument is TRUE, the statement following the while will be executed. When guess becomes equal to i, the statement following the while will be skipped.
The while is followed by a compound statement that contains two statements:
{
i=guess;