"Bill Cunningham" <nos...@nspam.invalid> writes:
> I thought I would submit this function I wrote to the group for opinions
> on style. The function itself seems to work. I know sometimes not returning
> anything can lead to undefined behavior but with main returning int I
> believe int is considered by the standard as the default type.
There is no "default type". Prior to C99, declaring or defining a
function with no explicit type was equivalent to declaring or defining
it with a return type of int, and calling a function with no visible
declaration would cause the compiler to assume a return type of int.
Both rules have been removed from the language.
But this is irrelevant to the code you show below. Your t_range
function is defined to return a result of type double, and all possible
execution paths cause it to return a result of type double. That
includes the "return -1;"; the int value -1 is converted to double.
IMHO "return -1.0;" would be clearer.
> So the return
> 0 in main isn't necessary but the returns in t_range are. t_range means true
> range between security prices. Any opinions on how I can improve this
> function as far as style?
>
> #include <stdio.h>
>
> double t_range(double hi, double low, double pc)
IMHO ordering the first to parameters as "lo, hi" would be less
confusing than "hi, lo".
> {
> double ans1, ans2, ans3;
> ans1 = ans2 = ans3 = 0.0;
The above assignment is unnecessary, since you immediately assign values
to all three variables.
> ans1 = hi - low;
> ans2 = pc - low;
> ans3 = hi - pc;
And these assignments would be clearer as initializations:
const double ans1 = hi - low;
const double ans2 = pc - low;
const double ans3 = hi - pc;
The "const" emphasizes (and enforces) the fact that none of these
variables are ever modified after their initializations.
> if (ans1 > ans2 && ans1 > ans3)
> return ans1;
> else if (ans2 > ans3 && ans2 > ans1)
> return ans2;
> else if (ans3 > ans2 && ans3 > ans1)
> return ans3;
> else {
> return -1;
> }
> }
>
> int main(void)
> {
>
> double r;
> r = t_range(1.25, 1.37, .67);
> printf("%.2f\n", r);
> return 0;
> }
>
http://www.incrediblecharts.com/indicators/true_range.php
I'm not commenting on the algorithm; I see others have done so.
--
Keith Thompson (The_Other_Keith)
ks...@mib.org <
http://www.ghoti.net/~kst>
Will write code for food.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"