“此处使用时变量可能未初始化”Xcode 编译器警告
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39397148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Variable may be uninitialized when used here" Xcode compiler warning
提问by Abdelrahman Eid
So I wrote this little programthat 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;
}
The weird thing is if I delete that commented line the warning disappears, and if I initialize num1
individually it also disappears. Am I doing something wrong or is that a bug in Xcode?
奇怪的是,如果我删除该注释行,警告就会消失,如果我num1
单独初始化,它也会消失。我做错了什么还是Xcode中的错误?
回答by rmaddy
The line
线
int num1, num2, product, largestProduct = 0;
only initializes largestProduct
to 0
. None of the other variables on that line are explicitly initialized.
仅初始化largestProduct
为0
. 该行上的其他变量均未显式初始化。
It's arguably poor practice to declare multiple variables on one line.
在一行上声明多个变量可以说是一种糟糕的做法。
I would suggest:
我会建议:
int num1 = 0;
int num2 = 0;
int product = 0;
int largestProduct = 0;
This is easier to read and debug.
这更易于阅读和调试。
But if you really want one line, do:
但是,如果您真的想要一行,请执行以下操作:
int num1 = 0, num2 = 0, product = 0, largestProduct = 0;
回答by Ayush Goel
In addition to @rmaddy's answer, you could also move the line num1 = 0
above the second while loop. That way, when you actually use the variable num
, it would have an explicit initialisation value.
除了@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;
}