//giving that int a is a positive numberCode:void dosomething(int a){ if (!a) return; dosomething(a >> 0x1); printf("%d\",(a & 0x1));
//giving that int a is a positive numberCode:void dosomething(int a){ if (!a) return; dosomething(a >> 0x1); printf("%d\",(a & 0x1));
I don't know, why don't you compile it and try it out? See what output you get for different inputs, and see if you can figure it out. If you're still stumped, post back with your best guess and explanation, and we'll help you sort out where you went wrong. Also, the string for printf looks incorrect.
There is also a missing closing brace, so the code would not even compile.
In addition to anduril's suggestion, try explaining what the individual statements and expressions do. Do you know what bit shifting and bitwise "and" achieve? If not, look them up, otherwise you will have no hope of explaining the code.
Is the printf() reachable in this code? It looks like it's set up to give a binary printing of an int, but the printf() will need to be reachable to do that.
> Is the printf() reachable in this code?
It seems like it would be a good exercise for you to do as well then
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I just did it, but I'm not entirely sure if my explanation for what I saw is correct. It does reach the printf(), but it does so only after returning (when the variable has reached 0).
The only explanation I could think of is that the function is returning you to itself (?), and that it will do this as many times as the recursion was called.
I need to get out of here, you people are trying to brainwash me with book-learn'in! :P
As Salem said, you need to do the exercise as well.
The point of a recursive function is that it calls itself sequentially and, when it returns, backs out sequentially. All you've described is that happens on the most deeply nested call. You also need to consider that, to return control to the (original caller) each call of the recursive function needs to return.
"...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson