如果.. else号小于,则无法访问的代码

Hon*_*nza 11 c conditional-statements

假设我们在C(或类似语言)中有以下代码:

if (x < 10)
  do_work1();
else if (x < 5)
  do_work2();
Run Code Online (Sandbox Code Playgroud)

在某些情况下,是否会执行此条件的第二个分支?编译器是否会警告无法访问的代码?

Mik*_*ike 21

Will the second branch of condition be executed in some case?

  • 是的,它有可能,它取决于代码中还有什么以及编译器选择如何处理代码.

Shouldn't compiler warn about unreachable code?

  • 不,它不能,因为不能保证它无法到达

以此为例:

int x = 11;

void* change_x(){
   while(1)
      x = 3;
}

int main(void) 
{
    pthread_t cxt;
    int y = 0;
    pthread_create(&cxt, NULL, change_x, NULL);
    while(1){
        if(x < 10)
            printf("x is less than ten!\n");
        else if (x < 5){
            printf("x is less than 5!\n");
            exit(1);
        }
        else if(y == 0){    // The check for y is only in here so we don't kill
                            // ourselves reading "x is greater than 10" while waiting
                            // for the race condition
            printf("x is greater than 10!\n");
            y = 1;
        }
        x = 11;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

并输出:

mike@linux-4puc:~> ./a.out 
x is greater than 10!
x is less than 5!      <-- Look, we hit the "unreachable code"
Run Code Online (Sandbox Code Playgroud)

  • 缺少任何`volatile`属性(对于C11之前的编译器)或内存障碍,编译器不必担心`printf("x小于5!\n");`并且确实会优化`main()`转换为甚至不包含该语句的目标代码,从而向您显示它对可能可访问的语句的关注程度.编译器没有警告的原因不是"不能保证它不可达",因为它对于定义的执行是无法访问的,并且编译器只关心定义的执行. (6认同)
  • 来自C11的J.2节未定义的行为:"程序的执行包含数据竞争(5.1.2.4)." (3认同)

gab*_*ish 1

第二个分支将不会被执行,编译器不应警告无法访问的代码。