Reputation: 23
I am working on a quiz with C, but I ran into a problem. Why is C looping the if statement "if (ans==true)"? I know this because the variable sum is a crazy number like 32767.
#include <stdio.h>
#include <stdbool.h>
bool askQuestion(char question[100],int answer){
int userAns;
printf("%s \n",question);
scanf("%d",&userAns);
if (userAns==answer){
printf("Correct \n");
return(true);
}
else{
printf("Wrong \n");
return (false);
}
printf("ERROR ERROR ERROR!");
}
int main(void)
{
bool ans;
int sum;
ans = askQuestion("yoyoyo",10);
if (ans==true){
sum+=1;
}
printf("Your score was %d/5",sum);
return 0;
}
EDIT: I didn't initialize the sum variable. My bad.
Upvotes: 1
Views: 82
Reputation: 1702
There is no looping involved, sum
is uninitialized therefore it's value is indeterminate. Easy fix,
Initialize sum:
int sum = 0;
Also you might want to check the return value of scanf()
in case an input error occurred,
if (scanf("%d", &userAns) != 1)
{
fprintf(stderr, "Scanf conversion error.\n");
exit(EXIT_FAILURE); /* #include <stdlib.h> */
}
Upvotes: 4
Reputation: 212198
Since sum
is not initialized, sum += 1
is undefined behavior.
Upvotes: 2