#include <stdio.h>
void main(void)
{
int price;
scanf("%d", &price);
switch (price)
{
case 1000: // what i want - case pay >= 1000
// code (no break - intentional)
case 500: // ....... - case pay >= 500
// code
default:
break;
}
}
I'm new to this. Is there any alternative to switch
without break
and also able to use comparisons, not constant, in a switch
?
CodePudding user response:
Just series of if
statements then :
if (price >= 1000) {
// do something
}
if (price >= 500) {
// do some more stuff
}
- You may also want to use
#define
for those magic numbers(1000, 500 ...)
. Or Enumerate them usingenum
. - Although
switch()
looks like a function, it's a statement block.
CodePudding user response:
As others have said, this problem is better suited to consecutive if
blocks than to a switch
statement (where the use of deliberate fall-through is frowned-upon by many in the C programming world).
However, if you want to divide a number into ranges of fixed-size blocks (in your case, that size is 500), then you can divide your number by that block-size and use the result as the switch
variable. Also, note that the default
case doesn't have to be the final case – it can be anywhere, even first.
In the below example, because of the fall-through (i.e. no break;
statements in any of the case
blocks), the case 0:
code will be run for any input; for inputs less than 500 (i.e. the integer division will result in 0), only that case will execute. For numbers in the range 500 thru 999 (division will give 1), the case 1
and case 0
code will run; and, for numbers >= 1000, the default
case will run, followed by the other two blocks. (This code requires a positive value for price
!)
#include <stdio.h>
int main(void)
{
int price = 0;
printf("Price: ");
int s = scanf("%d", &price);
if (s != 1 || price < 0) {
printf("Invalid price!\n");
}
else {
switch (price / 500) {
default:
printf("Price is >= 1000!\n");
case 1:
printf("Price is >= 500\n");
case 0:
printf("Price is anything\n");
}
}
return 0;
}
As I have said, I would generally not recommend using a switch
in cases (poor pun) like this; but, that advice notwithstanding, it is then actually quite easy to add extra blocks/conditions, such as code for prices in the 1000 - 1499 range, where you could just insert a case 2:
block to the code. Furthermore, when the number of 'ranges' becomes sufficiently large (say, more than 3), then it does arguably become clearer to use such a switch
, rather than a chain of if
statements/blocks.
CodePudding user response:
Use chained if … else
statements:
if (1000 <= price)
{
// Things for price 1000 or more.
}
else if (500 <= price)
{
// Things for price 500 or more.
}
else
{
// Things for other cases.
}