void print_binary(int number)
{
if (number){
print_binary(number/2);
putc((number % 2) ? '1' : '0', stdout);
}
}
int main(void) {
print_binary(8);
}
The code above returns "1000". But when I reverse the two lines in print_binary()
and write it like this:
void print_binary(int number)
{
if (number){
putc((number % 2) ? '1' : '0', stdout);
print_binary(number/2);
}
}
the string is "0001".
I can't understand why this happens. Any explanation is appreciated. Thanks
In first code sample, execution goes like this:
print_binary(8/2)
print_binary(4/2)
print_binary(2/2)
print_binary(1/2) // 1/2 = 0 => this is terminating condition of recursion
// stack windup from here
putc((1 % 2) ? '1' : '0', stdout); --> output 1
putc((2 % 2) ? '1' : '0', stdout); --> output 0
putc((4 % 2) ? '1' : '0', stdout); --> output 0
putc((8 % 2) ? '1' : '0', stdout); --> output 0
Hence, the output is 1000
.
In second code sample, execution goes like this:
putc((8 % 2) ? '1' : '0', stdout); --> output 0
print_binary(8/2)
putc((4 % 2) ? '1' : '0', stdout); --> output 0
print_binary(4/2)
putc((2 % 2) ? '1' : '0', stdout); --> output 0
print_binary(2/2)
putc((1 % 2) ? '1' : '0', stdout); --> output 1
print_binary(1/2) // 1/2 = 0 => this is terminating condition of recursion
// stack windup from here and nothing to do after last
// recursive call
Hence, the output is 0001
.
When you call a function, program puts the current address into stack memory where stack pointer points so it could come back when the execution ends and jumps to function's address. Stack is a LIFO (Last In First Out) structure so when you call a function, program finishes the instructions in the function than it turns back where it been. that's why putting order changes.
void print_binary(int number)
{
if (number){
putc((number % 2) ? '1' : '0', stdout); // 1st instruction
print_binary(number/2); // 2nd instruction
}
}
The program works like this:
So the output is 0001
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.