C: Looping without using looping statements or recursion

前端 未结 16 2094
走了就别回头了
走了就别回头了 2021-02-04 07:56

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

16条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-04 08:56

    With blocking read, signals and alarm. I thought I'd have to use sigaction and SA_RESTART, but it seemed to work well enough without.

    Note that setitimer/alarm probably are unix/-like specific.

    #include 
    #include 
    #include 
    #include 
    #include 
    
    volatile sig_atomic_t counter;
    volatile sig_atomic_t stop;
    
    void alarm_handler(int signal)
    {
      printf("%d\n", counter++);
      if ( counter > stop )
      {
        exit(0);
      }
    }
    
    int main(int argc, char **argv)
    {
      struct itimerval v;
      v.it_value.tv_sec = 0;
      v.it_value.tv_usec = 5000;
      v.it_interval.tv_sec = 0;
      v.it_interval.tv_usec = 5000;
      int pipefds[2];
      char b;
    
      stop = 10;
      counter = 1;
    
      pipe(pipefds);
    
      signal(SIGALRM, alarm_handler);
    
      setitimer(ITIMER_REAL, &v, NULL);
    
      read(pipefds[0], &b, 1);
    }
    

提交回复
热议问题