Page 72 - Programming Microcontrollers in C
P. 72
Functions 57
will yield
x = 7*(y) +(y);
which is the wrong answer. The problem can be easily corrected by
wrapping parentheses around the whole macro as
#define times_two(x) ((x)+(x))
Remember, always place any argument of a macro within parenthe
ses and always place the entire macro definition in parentheses.
Note that there is no semicolon at the end of the macro defini
tion. There should not be. If a semicolon were placed at the end of a
macro definition, extra semicolons would be entered into expres
sions containing macros with unpredictable results.
The function prototype
double sqr( double );
notifies the compiler that the function returns a double and takes a
double argument.
Inside of the main function, the for loop
for(i=1;i<11;i++)
{
c=sqr(i);
printf(“\t%d\t%f\t%f\n”,i,c,square(c));
}
is used to calculate the several results. The variable c is of the type
double, and i is an int. The expression c=sqr(i) will be ac
cepted by the compiler. This function returns a double which can be
stored in c. The argument is an int, but the compiler recognizes
that sqr requires a double argument and converts i to a double
before it is sent to the function sqr().
The code in the function sqr() is a restatement of a square root
operation that we saw earlier. In this case, the function processes
floating-point numbers rather than the integers used before. Three
double variables are needed. The variables x1 and x2 are the current
and last values found in the Newton iteration. As the result converges
to the correct value for the square root, several things happen. Vari
ables x1 and x2 become equal. The square of x2, or x1 for that
matter, becomes equal to x. The product of x1 and x2 becomes