Why are empty expressions legal in C/C++?

后端 未结 11 1736
囚心锁ツ
囚心锁ツ 2020-11-29 11:21
int main()
{
  int var = 0;; // Typo which compiles just fine
}
相关标签:
11条回答
  • 2020-11-29 11:32

    I honestly don't know if this is the real reason, but I think something that makes more sense is to think about it from the standpoint of a compiler implementer.

    Large portions of compilers are built by automated tools that analyze special classes of grammars. It seems very natural that useful grammars would allow for empty statements. It seems like unnecessary work to detect such an "error" when it doesn't change the semantics of your code. The empty statement won't do anything, as the compiler won't generate code for those statements.

    It seems to me that this is just a result of "Don't fix something that isn't broken"...

    0 讨论(0)
  • 2020-11-29 11:33
    while (1) {
        ;  /* do nothing */
    }
    

    There are times when you want to sit and do nothing. An event/interrupt driven embedded application or when you don't want a function to exit such as when setting up threads and waiting for the first context switch.

    example: http://lxr.linux.no/linux+v2.6.29/arch/m68k/mac/misc.c#L523

    0 讨论(0)
  • 2020-11-29 11:35

    OK, I’ll add this to the worst case scenario that you may actually use:

    for (int yy = 0; yy < nHeight; ++yy) {
        for (int xx = 0; xx < nWidth; ++xx) {
            for (int vv = yy - 3; vv <= yy + 3; ++vv) {
                for (int uu = xx - 3; uu <= xx + 3; ++uu) {
                    if (test(uu, vv)) {
                        goto Next;
                    }
                }
            }
        Next:;
        }
    }   
    
    0 讨论(0)
  • 2020-11-29 11:36

    When using ;, please also be aware about one thing. This is ok:

    a ? b() : c();
    

    However this won't compile:

    a ? b() : ; ;
    
    0 讨论(0)
  • 2020-11-29 11:37

    The most common case is probably

    int i = 0;
    for (/* empty */; i != 10; ++i) {
        if (x[i].bad) break;
    }
    if (i != 10) {
        /* panic */
    }
    
    0 讨论(0)
  • 2020-11-29 11:41

    There are already many good answers but have not seen the productive-environment sample.

    Here is FreeBSD's implementation of strlen:

    size_t
    strlen(const char *str)
    {
        const char *s;
    
        for (s = str; *s; ++s)
            ;
        return (s - str);
    }
    
    0 讨论(0)
提交回复
热议问题