我像这样用clang编译以下代码:

clang main.cpp -Werror -Wconditional-uninitialized

码:
    #include <stdio.h>

    bool captureSupported() {
      return true;    // it makes no difference to the compiler if it returns true or false
}

// false - success, true - failure
bool capture(char **ptr) {
  // it makes no difference to the compiler if it is commented out or not
  // *ptr = (char*)"captured";
  return true;    // it makes no difference to the compiler if it returns true or false
}

void foo() {
  char *ptr;
  bool capture_raw = true;

  if(captureSupported() && (!capture(&ptr)) ) { // compilation warning/error
//  if(true && (!capture(&ptr)) ) {             // no warning/error
//  if(false && (!capture(&ptr)) ) {            // no warning/error
//  if(captureSupported() && (!false) ) {       // no warning/error
//  if(captureSupported() && (!true) ) {        // no warning/error
    capture_raw = false;
  } else {
    printf("cannot capture\n");
  }

 if(capture_raw) {
    ptr = (char*)"raw captured";
  }

  printf("%s", ptr);
}

int main() {
  foo();
  return 0;
}

有人可以向我解释为什么编译结果是:
main.cpp:33:16: error: variable 'ptr' may be uninitialized when used here [-Werror,-Wconditional-uninitialized]
  printf("%s", ptr);
               ^~~
main.cpp:16:12: note: initialize the variable 'ptr' to silence this warning
  char *ptr;
           ^
            = nullptr
1 error generated.

没有初始化ptr的可能路径。还是如果编译器非常聪明,以至于无法确定capture()对其进行了初始化,为什么要注释掉“ifs”,使编译器感到高兴呢?

最佳答案

您正在以错误的方式阅读警告。



这意味着编译器无法证明变量在使用前已初始化,而不是能够证明未初始化。

07-24 18:27
查看更多