C: Looping without using looping statements or recursion

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

    You can do this by nesting macros.

    int i = 1;
    
    #define PRINT_1(N) if( i < N ) printf("%d\n", i++ );
    #define PRINT_2(N) PRINT_1(N) PRINT_1(N)
    #define PRINT_3(N) PRINT_2(N) PRINT_2(N)
    #define PRINT_4(N) PRINT_3(N) PRINT_3(N)
    :
    :
    #define PRINT_32(N) PRINT_31(N) PRINT_31(N)
    

    There will be 32 macros in total. Assuming size of int as 4 bytes. Now call PRINT_32(N) from any function.

    Edit: Adding example for clarity.

    void Foo( int n )
    {
        i = 1;
    
        PRINT_32( n );
    }
    
    
    void main()
    {
        Foo( 5 );
        Foo( 55 );
        Foo( 555 );
        Foo( 5555 );
    }
    

提交回复
热议问题