C: Looping without using looping statements or recursion

前端 未结 16 1836
走了就别回头了
走了就别回头了 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

    #include 
    
    int callback(const void *a, const void *b) {
        static int n = 1;
    
        if (n <= N)
            printf("%d\n", n++);
    
        return 0;
    }
    
    int main(int argc, char *argv) {
        char *buf;
        /* get N value here */
    
        buf = malloc(N);  // could be less than N, but N is definitely sufficient
        qsort(buf, N, 1, callback);
    }
    

    I think it doesn't count as recursion.

提交回复
热议问题