C: Looping without using looping statements or recursion

前端 未结 16 2092
走了就别回头了
走了就别回头了 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 09:00

    I'd go for using longjmp()

    #include 
    #include 
    
    void do_loop(int n) {
      int val;
      jmp_buf env;
    
      val = 0;
    
      setjmp(env);
    
      printf("%d\n", ++val);
    
      if (val != n)
        longjmp(env, 0);  
    }
    
    int main() {
      do_loop(7);
      return 0;
    }
    

提交回复
热议问题