Greetings , today when I try something new(Concept and style that suddenly pop out in my mind) , I encountered a few problems which I don't understand why it happened.
The Code
// This program would get two numbers from user , and request for an arithmetic operator , and carry out arithmetic.
#include <stdio.h>
int main(void)
{
int fNum;
int sNum;
int status = 1;
int operator;
int ans;
printf("Enter the first operand :");
while(scanf("%d" , &fNum) == 0)
;
printf("Please enter the second operand :");
while(scanf("%d" , &sNum) == 0)
;
printf("Which operator you wanted to use\n");
printf("1 for +\n2 for -\n");
while(status)
{
scanf("%d" , &operator);
status = 0;
switch(operator)
{
case 1:
ans = fNum + sNum;
break;
case 2:
ans = fNum - sNum;
break;
default:
status = 1;
}
}
printf("The answer is %d\n" , ans);
return 0;
}
My Analysis and Question
First part :
1.)There's one thing I don't understand , when I try to run this code , I get an warning message from the compiler , "C:\Users\Znet\Documents\Pelles C Projects\Test1\Test.c(10): warning #2229: Local 'ans' is potentially used without being initialized." , but of course I still can run the program since it's not an error message.
2.)I just wonder why this warning message occured , out of curiosity , instead of just declaring the variable ans
, I initialize it with an integer value(0 or any whole number) , and the warning message just gone.What causes this to happen??Is it because the variable ans
is used in a switch
statement that's why we should assign a value to it before using it?Because all the time (when i'm coding other program) I don't even initialize a variable with a value before using it to store a value evaluated by an arithmetic expression.
Second part :
1.)The problem arouse inside the switch
statement , when the program is asking user to enter either number 1
or 2
for the arithmetic sign.
2.)If i enter an integer not within 1 and 2 , the program will not proceed but instead waited me to reenter the correct value , which is my main intention.
3.)But the thing is , if the value I enter is not an integer but instead a character , the program would just freeze , the cursor is still blinking but it's not respond to my keyboard input.In the end , I have to kill the program in order to close it.
4.)I know there're many ways for me to code this kind of program , but I just wonder why in this code , this situation would happened??
Thanks for reading my problem , hope to get explanations and knowledges from you guys :)