Reputation: 13
I'm learning C and I have one problem right now.
This is my part of code for a guessing number game, it's simple:
int secretNumber = 13;
int guess;
while (guess != secretNumber) {
printf("Enter a number: ");
scanf("%d", &guess);
}
printf("Win!");
And I receive the following errors:
- Using uninitialized memory
- uninitialized locar variable 'guess' used.
- return value ignored 'scanf'.
Upvotes: 1
Views: 1341
Reputation: 831
Your problem is because the guess
is uninitialized and you are comparing it in the while loop in the beginning.
In this case, it is better to construct it using in the do {} while()
form. This way, the comparison is done after you got the value for the guess
variable:
int secretNumber = 13;
int guess;
do {
printf("Enter a number: ");
scanf("%d", &guess);
} while (guess != secretNumber);
printf("Win!");
You are going to have some warning in the scanf()
as well because you are not checking the return value.
To fix that as well, you can check like this:
if (scanf("%d", &guess) != 1) {
print("invalid input, try again\n");
}
Upvotes: 5