Simple C switch() statement problem

Associate
Joined
5 Oct 2003
Posts
657
Location
London
Hi,
Am trying to complete some work for university but have hit a brick wall,
previously in my code i have used a switch() no problem, but now when trying to use the below i get a error C2059: syntax error : '>', & '>=':


Code:
switch (gross_pay)

	{
		case>0 && case<=300 : tax = .15 * gross_pay;
				   		break;
					

		case>=301 && case<=500 : tax = 45 + .2 * (gross_pay - 300);
					   		break;
					

		case>=501 && case<=650 : tax = 85 + .25 * (gross_pay - 500);
					   break;
					

		case>=651 : tax = 122.5 + .3 * (gross_pay - 650);
			    break;
			

		default :  ;
		
	}

	printf("Total Tax payed is %d\n", tax);

Can anyone explain why? gross_pay is working fine and its an integral so no worries there, its just the syntax error i can't get around for some reason :(

Any help greatly appreciated.
 
Hi,
Not 100% sure with C but I don't think you can have switch with that syntax. The case has to be followed with something the switch(variable) can be compared with (matches). Gross pay will be a float of some kind, so the case has to be followed by a float... not the multiple conditions you have tried.

As I said, not the worlds best at C, but that's what I think the issue is.
 
Yeah - Haven't touched C for a while I'm pretty sure the cases have to be for specific values of grosspay, e.g. case 10000:

You could do those conditions with

if (condition)
..
else if (condition)
..
else if (condition)
..
else
..
 
Last edited:
Each case must be an integer constant. So you cant put your expressions there im afraid. Use an if/else if/else structure as suggested to do what you want.
 
Back
Top Bottom