#include<stdio.h>
void main(){
char operator;
double a, b;
printf("enter an operand(+,-,*,/)");
scanf("%c",&operator);
printf("enter two operands");
scanf("%lf %lf",&a,&b);
switch(operator){
case '+': printf("%lf is the output of a & b",(a+b)); break;
case '-': printf("%lf is the output of a & b",(a-b)); break;
case '*': printf("%lf is the output of a & b",(a*b)); break;
case '/': printf("%lf is the output of a & b",(a/b)); break;
}
}
I know that only an integer is allowed after a case. I also know that any character written inside single inverted commas writtens an ascii interger.
In this the argument inside the switch statement is a character, switch(operator);
.
How will that equate with an integer inside the case? case '+':
The condition in the switch
-statement needs not to be type int
exactly but "any expression of integer type (char, signed or unsigned integer, or enumeration)" (cf., for example, switch statement documentation at cppreference ). So using variable operator
of type char
as condition in the switch
-statement is ok.
The constant expressions in each case:
-label are converted to the promoted type of expression ( char
in your case) and the result of evaluating the condition is then compared with the (converted) value of the expression. A constant expression of type char like '+'
, '-'
is therefore OK, too.
In the end, the promoted type of the condition is char
, each constant in your case:
-statements is of type char
, and therefore char
is compared with char
.
Note that the char-"value" of constant '+'
is it's 8 bit ASCII-value, which is 43
. Also, if one enters +
in the console when using scanf("%c",&operator)
, the "value" of operator
will be the 8 bit ASCII-value of +
, too, ie 43
. In this case, the switch-statement will compare 8 bit 43
with 8 bit 43
...
Hope it helps.
char
is just the 8 bit (mostly) integer
so case '+':
is an equivalent of the to case 43:
as 43 is the ascii code of '+'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.