代码之家  ›  专栏  ›  技术社区  ›  Martijn

无法访问的代码:错误还是警告?

  •  20
  • Martijn  · 技术社区  · 15 年前

    这是一个语言设计问题:

    你认为 无法访问的代码 (在编程语言中)应该 警告 (即“无论如何报告问题和编译”)或 错误 (“拒绝编译”)?

    我个人强烈地认为这应该是一个错误:如果程序员写了一段代码,那么它应该始终具有实际运行它的意图。 一些 脚本。但是,例如,C编译器似乎不同意这一点,只是报告了一个警告。

    注意:我认识到好的死代码检测是一个非常困难的问题,但这不是这个问题的焦点。

    下面是一些代码片段的示例,其中一些语句显然无法访问:

    return;
    foo();
    

    ——

    throw new Exception();
    foo();
    

    ——

    if (...) {
      return;
    } else {
      throw new Exception();
    }
    foo();
    
    12 回复  |  直到 10 年前
        1
  •  12
  •   Joachim Sauer    15 年前

    if (false) {
      doStuffThatITemporarilyDisabled();
    }
    

        2
  •  28
  •   Justin    15 年前

    public bool ShowMenu()
    {
        return true;
        /* The standard implementation goes here */
    }
    

        3
  •  24
  •   anon    15 年前

        4
  •  8
  •   No Refunds No Returns    15 年前

        5
  •  8
  •   Razzie    15 年前

        6
  •  4
  •   unwind    15 年前

        7
  •  3
  •   Vatine    15 年前

        8
  •  2
  •   Roalt    15 年前

    int i = 2, j = 3;
    int result = 0;
    
    // FIXME: Commented out for now because I have to recheck calculation
    if (false) {
      result = i*2+j+3+i*j;
    }
    
    System.out.println("Result of difficult calculation = "+result);
    

        9
  •  2
  •   plinth    15 年前

        10
  •  2
  •   eflorico    15 年前

        11
  •  2
  •   johnchen902    11 年前

    // C code
    #define ENABLE_FOO //Comment off this to turn off foo(void);
    int foo(void)
    {
    #ifdef ENABLE_FOO
        // Do actual stuff.
        int returnVaue = 2;
        // ...
        return returnValue;
    #else
        return 0; // Turned off
    #endif
    }
    // Compiling using clang, enforcing dead code detection:
    // clang main.c -Wall -Werror
    

    // Class
    #define MYCLASS_ENABLE_FOO // Comment off to enable -[MyClass foo]
    @interface MyClass : NSObject
    #ifdef MYCLASS_ENABLE_FOO
    - (int)foo;
    #endif
    @end
    // The like is done in implementation.
    // Invoking:
    int main(int argc, char **argv)
    {
        MyClass *object = [[MyClass alloc] init];
        int value = ([object respondsToSelector:@selector(foo)]) ? // Introspection.
                    [object foo] : 0;
        printf("Value: %d", value);
        return 0;
    }
    
        12
  •  2
  •   david.pfx    11 年前

    推荐文章