Reputation: 901
So I wrote this little 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;
}
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?
Upvotes: 0
Views: 23167
Reputation: 3144
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.
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;
}
Upvotes: 0
Reputation: 318774
The line
int num1, num2, product, largestProduct = 0;
only initializes largestProduct
to 0
. None of the other variables on that line are explicitly initialized.
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;
Upvotes: 2