On 13 Mar 2005 21:32:52 -0800, "lovecreatesbeauty"
<> wrote in comp.lang.c:
> I ever missed a `return' statement when write a function `int
> HighDigit(Num)' to get the highest digit of an integer.
It is actually legal in C to omit a return statement from a function
with a return type other than void. Rather foolish, but legal.
> But even if the `return' statement is ignored the function still can
> obtain an `correct' return value when the argument `Num' is larger than
> or equal to the Macro `NUM_SYS'.
Now here the C standard does have something to say. If you miss a
return statement in a function that has a non-void return type, and if
the calling code uses the return value in any way, then the behavior
is undefined.
> If the argument is less than the Macro, the function without a `return'
> get an undefined value. I've made a test on Ms Windows 2000 and VC 6.
Actually the result is always undefined, a term with a precisely
defined meaning in the C language. It is just in some cases the value
is what you expect it to be, and in other cases it is not.
> Thank you in advance for explaining why.
When you produce undefined behavior, the C language no longer
specifies what will happen. One possible result of undefined behavior
is that, in some cases, the program "works" the way you think it
should.
> And would you please comment on this algorithm? Thank you.
>
>
>
>
> i.e.
> Num HighDigit(Num)
> ======================
> 123 | 1
> 321 | 3
> 2 | 2
> 10 | 1
> ______________________
>
>
>
>
>
> The code I write is:
>
>
> //highdigit.h
>
> #ifndef _HIGH_DIGIT_H_
> #define _HIGH_DIGIT_H_
This is something you should not do. All identifiers beginning with
two underscores or an underscore followed by an uppercase letter are
reserved for the compiler, and not to be used in your code.
> #define NUM_SYS 10 //number system, decimal assumed as default
Either your function always works with base 10, in which case you
don't need the definition in the header but only in the source code
file with the function body. And it is not a default, it is the only
value. Or you want it to work on various bases, in which case the
base should be a function parameter as in functions like strtol() in
the standard library.
> int HighDigit(int Num);
You could make this:
int HighDigit(int Num, int base);
> #endif //_HIGH_DIGIT_H_
>
>
> //highdigit.c
>
> #include "highdigit.h"
>
> int HighDigit(int Num){
> while (Num >= NUM_SYS){
> Num /= NUM_SYS;
> }
>
> //return Num; //This statement be missed by me at first.
> }
....and likewise:
int HighDight(int Num, int base)
{
assert(base > 0);
while (Num >= base)
{
Num /= base;
}
return Num;
}
--
Jack Klein
Home:
http://JK-Technology.Com
FAQs for
comp.lang.c
http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++
http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html