By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,384 Members | 671 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,384 IT Pros & Developers. It's quick & easy.

can Logical operator use in the switch case in the case

P: 1
switch(temp)
{
case (temp<=20):
printf("Hello!");
default:
printf("good old");
}
can i use the case (temp<=20): in the program
Jun 22 '17 #1
Share this Question
Share on Google+
2 Replies


weaknessforcats
Expert Mod 5K+
P: 9,197
No.

The case has to be a single integer value known to the compiler since the case is compiled in to the object code.

You can try an expression with a compile and you will see the compiler error out on the code.
Jun 22 '17 #2

Expert 100+
P: 2,398
You could create a new variable to express the various meangful ranges of temp and then switch on that new variable. You may decide this isn't worth the effort. Personally, i would put the case blocks in the if-elseif-else and not have a switch at all.

Expand|Select|Wrap|Line Numbers
  1. enum { LE20, GT20_LE40, GT40 } tempRange;
  2.  
  3. if (temp <= 20)
  4.    tempRange = LE20;
  5. else if (temp <= 40)
  6.     tempRange = GT20_LE40;
  7. else
  8.     tempRange = GT40;
  9.  
  10. switch (tempRange) {
  11.     case LE20:
  12. ...
Jun 23 '17 #3

Post your reply

Sign in to post your reply or Sign up for a free account.