hi: I want to use recursion function to transform a integer from binary form to ascii form. But the result is wrong.I don't why ,please help to analyse.
soure code:
void binary_to_ascii(unsigned int value) { unsigned int quotient; quotient = value/10; if(quotient !=0 ) binary_to_ascii(quotient); putchar(value%10+'0'); } int main() { while(1){ binary_to_ascii(4267); } }
I want to produce characters '4','2','6','7' in sequence. but the result is '4','4','4'. I don't know what is wrong with my code.
"It also requires some way to pass parameters & maintain local variables so that each "recursion" doesn't corrupt the data & parameters of previous recursions; ie, it requires that the functions are reentrant."
Not always needed. The "standard" recursive function fac() who every school uses as prime example of recursion can work inplace. A lot of linear recursive functions just needs one set of registers.
It also requires some way to pass parameters & maintain local variables so that each "recursion" doesn't corrupt the data & parameters of previous recursions; ie, it requires that the functions are reentrant.
Most 'C' compilers achieve this by using the stack, so that their functions are inherently reentrant - Keil C51 does not do this and its functions are inherently not reentrant.
This is the same reason why Keil C51 has issues with function pointers - as previously explained: http://www.keil.com/forum/17469
Again, this is down to the specific features of the 8051 architecture and, again, you must not just assume that the 8051 is "just another processor" - it isn't!
A recursive function requires a stack for storing the return values - check how large this stack must be for each iteration of a recursive function.
It is trivial to rewrite a very large group of recursive functions into iterative functions. In this case, the trivial implementation will produce the characters in reverse order - but each iteration only needs one byte to store one character until they are ready to be emitted in the correct order.
Recursion is a very useful concept. But it is best left for problems where the complexity of storing state information and making subdivision decisions gets very complex with a non-recursive method.
Any linear recursive algorithm can be trivially rewritten as an iteration. Many branching recursive algorithms (tree walking for example) can be trivially rewritten with an explicit state queue. It's quite seldom that a iterative solution can't be implemented in an obvious way.
For the same reasons that function pointers are best avoided in C51 - see your other thread: http://www.keil.com/forum/17469/
Any recursive algorithm can be restructured into an iterative one - or why not just use sprintf??!
Look up recursive or reentrant in the C51 user's manual. You will see that you must use the keyword reentrant so that a pseudo stack can be built to save any registers used in the reentrant function. Bradford
View all questions in Keil forum