Use of null statement in C

前端 未结 12 1892
挽巷
挽巷 2020-11-29 09:12

What are typical uses of null statement

;

in C ?

I know that it is basically used to skip expression where it is expected

相关标签:
12条回答
  • 2020-11-29 09:52

    The only uses I can think of are:

    1- At the end of a loop, where the operations are already encoded within the loop statements. e.g. while(a[i--]);

    2- At the end of a label, where no operation is needed to be done. e.g. Label: ;

    0 讨论(0)
  • 2020-11-29 09:53

    It's more of a null expression rather than a null statement, but it's often found in for loops.

    for (;;)                 // Loop "forever"
    
    for (int i=10; i--; )    // 9..0
    

    etc

    0 讨论(0)
  • 2020-11-29 09:53

    i was wondering how to write a null expression into the inline if and came up with this. it compiles and works.

    condition ? x = 1 : "do nothing";
    

    fun stuff.

    0 讨论(0)
  • 2020-11-29 09:55
    while (somethingWithSideEffects()) ;
    
    0 讨论(0)
  • 2020-11-29 10:02

    It's typically the side-effect of a code block that was stripped by the preprocessor, like

    #if DEBUG
        #define ASSERT(_x) Assert(_x)
    #else
        #define ASSERT(_x)
    #endif
    
    
    ASSERT(test);    // Results in null statement in non-debug builds
    

    That, or in loops where your condition already contains whatever needs to be done in each iteration.

    0 讨论(0)
  • 2020-11-29 10:02

    Example:

     while (!kbhit())
         ;
    

    Should be self-explanatory.

    0 讨论(0)
提交回复
热议问题