Tvaṣṭā
Tvaṣṭā

Reputation: 131

How do I write a recursive delay function in C

as part of a fun coding session, my friend was working on writing a delay function in C, I don't primarily program in C, I used to. However, I wanted to write one using recursion but haven't been quite able to achieve what I wanted my program to do....which is the delay, say of 20ms.I guess I am missing some logic here..How do I write a delay function using recursion. At present my code looks like so, it needs to address a millisecond to seconds range.

    #include <stdio.h>
    #include <stdlib.h>

    void delay(unsigned long* d) {
        while(*d-- > 0){
           delay(d);
        }
    }

    int main()
    {
        unsigned long del = 200;
        delay(&del);
        return 0;
    }

Upvotes: 0

Views: 236

Answers (2)

unwind
unwind

Reputation: 399793

This looks like a very bad idea in general; in most environments where a busy-looping delay make sense, you really can't afford the stack this is going to consume just to delay.

That said, I think it's a failure to make it pointer-oriented, since that shares the value weirdly across invocations.

It should just be something like:

void delay(unsigned long d)
{
  if(d > 0)
    delay(d - 1);
}

Of course there is absolutely no connection between d the the actual delay generated, that depends on a whole bunch of factors which the OP didn't disclose, and I fail to take this seriously enough to try to get the information.

Also the while kind of spoils the "this is recursive" mindset.

Upvotes: 3

AnthonyLambert
AnthonyLambert

Reputation: 8830

Bad, Bad, Bad....

Firstly this will not work in practice, if you pass in a large number to get any worthwhile delay you will run out of stack space and the program will break with an error or cause some random undefined behavior.

Also you don't state what platform you running on but it is usually better to call the operating systems wait function so the act of waiting doesn't hog the current core and the current process can yield to other processes/threads on the system or if there is no work to do save power by running slowly until needed.

Also how does the delay loop actually relate to real time? It will run at different speeds on different hardware, and also change dependent each time it runs on what else is running at the same time. To make it exact you we need to tie the loop to a clock or other hardware signal that allows you to track time like a hardware interrupt or some such.

Upvotes: 1

Related Questions