"Variable may be uninitialized when used here" Xcode 编译器警告

"Variable may be uninitialized when used here" Xcode compiler warning

所以我写了这个小program that gives this warning despite the fact that I have the variable initialized, not a duplicate question

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        int num1, num2, product, largestProduct = 0;

        while (num2 < 1000) {

            while (num1 < 1000) {

                product = num1 * num2;

                if (isPalindrome(product)) {

                    largestProduct = product>largestProduct?product:largestProduct;
                }

                num1++;
            }

            num1 = 0; //If I delete that line the warning disappears.
            num2++;
        }

       NSLog(@"%i", largestProduct);

    }
    return 0;
}

奇怪的是,如果我删除那条注释行,警告就会消失,如果我单独初始化 num1,它也会消失。我做错了什么还是 Xcode 中的错误?

int num1, num2, product, largestProduct = 0;

仅将 largestProduct 初始化为 0。 None 该行上的其他变量已显式初始化。

在一行中声明多个变量可以说是一种糟糕的做法。

我建议:

int num1 = 0;
int num2 = 0;
int product = 0;
int largestProduct = 0;

这更易于阅读和调试。

但如果你真的想要一行,请执行:

int num1 = 0, num2 = 0, product = 0, largestProduct = 0;

除了@rmaddy 的回答之外,您还可以将 num1 = 0 行移至第二个 while 循环上方。这样,当你实际使用变量 num 时,它就会有一个明确的初始化值。

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        int num1, num2, product, largestProduct = 0;

        while (num2 < 1000) {

            num1 = 0; //Value initialised here.

            while (num1 < 1000) {

                product = num1 * num2;

                if (isPalindrome(product)) {

                    largestProduct = product>largestProduct?product:largestProduct;
                }

                num1++;
            }

            num2++;
        }

       NSLog(@"%i", largestProduct);

    }
    return 0;
}