问题描述
我想写一个C函数将在标准输出,其中N是一个int型参数的函数打印1到N一种全每一行。该功能不能使用,同时,对,做-while循环,goto语句,递归和switch语句。是否可以?我想找到一个答案,因为这是一个挑战问题
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? I want to find an answer to this as this a challenge question
推荐答案
通过阻塞读,信号和报警。我想我必须使用的sigaction和SA_RESTART,但它似乎工作不够好,没有。
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.
需要注意的是setitimer函数/报警可能是UNIX /般特有的。
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);
}
这篇关于C:循环不使用循环语句或递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!