C: Looping without using looping statements or recursion

c, loops

Solution

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 <signal.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

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);
}

Problem

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?

Original source