The following code compiles and works as expected, despite one frustrating error in program flow that I don't understand ..
The loop in the middle of the main function works fine if I pass 2 or 5 as input. However, when I pass -3 or anything below zero (such as a character, which return -1), the loop continues forever and the program doesn't even pause for me to provide input for the scanf function ..
#include <stdio.h>
#include <stdlib.h>
void getNum(char * prompt, int*num)
{
printf("%s", prompt);
scanf("%d", num);
}
int main(int argc, char ** argv)
{
int num = -1;
while(num < 0) { // problem here
getNum("Number of times you go to the gym in a week: ", &num);
}
return EXIT_SUCCESS;
}
I wonder were the mistake is ..
I noticed something strange .. When I change the loop to a do-while loop it works just fine ..
int main(int argc, char ** argv)
{
int num;
do {
getNum("Number of times you go to the gym in a week: ", &num);
} while (num < 0); // this works fine ..
return EXIT_SUCCESS;
}
Also, for some reason, I recompiled the code and it worked fine ..
Can anybody explain this ?