C switch statement , variable error(For a calculator program source code)
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开发者_JAVA技巧 , 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 :)
First question:
The compiler is detecting that ans
is only getting a value assigned to it conditionally (for two specific cases in your switch statement). Some compilers warn about this and others do not. As a rule, it is always good practise to initialize any variable you create.
Second question:
This question has been answered many times before - see infinite scanf loop. The problem is that scanf only accepts an integer in this case. As mentioned in this link "Any character that doesn't match the format string causes it to stop scanning and leaves the invalid character still in the buffer." This is causing your while loop to never exit. If you are interested in more details, the link mentioned here should really help you.
Q: "warning #2229: Local 'ans' is potentially used without being initialized."
A: This means that ans can contain any value upon declaration (since stack variables aren't nulled out on declaration) - and since the compiler didn't see programming logic that guarantees that the variable is set when printed - it throws this warning. Doing
int ans = 0;
will remove it.
Q: 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.
A
.
do {
printf("Which operator you wanted to use\n");
printf("1 for +\n2 for -\n");
} while ( scanf("%d", &operator) != 1 );
scanf
returns the amount of matches --- if it doesn't match an integer, it will return 0. Therefore; Check the return value.
First Part
Compilers can give warning when you use a variable without having it explicitly initialized. This is because uninitialized variables can create nasty bugs in your code. For example consider the following code segment.
int main()
{
/* NOTE: 'f' is uninitialized */
int f, n;
printf ("\nn : ");
scanf ("%d", &n);
while (n)
f = f * n--;
printf ("\nfactorial = %d", f);
return 0;
}
In the above code the output of the program in undefined. f
is a local variable (automatic
), so when the main
starts to execute f
can have any value, ie garbage, and the factorial computation relies on the initial value of f
. So in such a case uninitialized variable will lead you to a catastrophe. To solve it you need to do int f = 1;
and you get the correct output. This is not an error, but can be a logical error, so the compilers help you with it, that you might not accidentally left a variable uninitialized. In your case it is not required to be initialized, so you can simply do ans = 0;
stop the warning.
Second Part
A character and an integer is interpreted differently. For example 12
are two characters, and also we can say that it is an integer. To input it as an integer you should use "%d"
and as characters scanf ("%c%c",&var1, var2);
as there are two characters. When you enter a character when the format string is "%d"
it will detect that the input is not an integer (it is a character), and will stop at that moment and will return. Nothing will be stored in the operator
variable. The scanf
returns the number of components it has read. In this case when it encounters that you have entered a character it would return 0
as it has not read in the input and has stopped. But when you input an integer it will read it correctly in operator
and return 1
. So keep a check like:
/* Ask for input while the user does not input a
* valid integer.
*/
while (scanf ("%d", &operator) != 1)
{
/* Body is entered whenever an invalid integer is entered */
/* Your message */
}
/* When the user inputs a valid integer the condition
* in 'while' loop is false and program continues
*/
精彩评论