I want to write a C function that will print 1 to N one per each line on the stdout where N is a int parameter to the function. The function should not use while, for, do-while loops, goto statement, recursion, and switch statement. Is it possible?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- R: eval(parse()) error message: cannot ope
- Index of single bit in long integer (in C) [duplic
write all possible output to a string first, and null terminate it where the output should stop.
this is a rather dirty solution, but given the limitations, all I can think of,
except for using assembler, off course.
Given that
MAX_INT==2147483647
on popular architectures, we only need to go up to+c(999999999)
. Typing out that initial string might take a while, though...This takes the integer N from the command line and prints out from 1 to N
N is not fixed, so you can't unrole the loop. And C has no iterators as far as I know.
You should find something that mimics the loop.
Or thinking outside the box:
(for example N is limited to 1000, but it is easy to adapt)
I'm very disappointed that this doesn't work. To me, the phrase "a function is called after any previously registered functions that had already been called at the time it was registered" suggests that it is possible to register atexit handlers after they have started to be called. That is, a handler can register another handler. Otherwise, how is it even possible for there to exist a function which has been called at the time another function is registered? But for me the call to atexit is returning 0 success, but not actually resulting in another call. Anyone know why, have I made some silly error?
By the way, not recursion because atexit doesn't call its parameter, it queues it to be called later. Obviously the C runtime contains a loop to call atexit handlers, but that loop exists whether you actually register any atexit handlers or not. So if this program contains a loop, so does every C program ;-)
If you know the upper limit of N you can try something like this ;)
Joke aside, I don't really see how you can do it without recursion or all the instructions you mentioned there. Which makes me more curious about the solution.
Edit: Just noticed I proposed the same solution as grombeestje :)