Thread: how to use range in switch-case

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    1

    Thumbs down how to use range in switch-case

    Hi! Guys

    Can anyone help me in knowing how can i specify a range in switch case.
    For example if the code in nested if else is as follows :

    if(i<0) printf("Negative");
    else if(i>0) printf("positive");
    else printf("No. is Zero");

    Now my point is how can one make this module using switch-case.

    Thanks And regards
    Himanshumad.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > Can anyone help me in knowing how can i specify a range in switch case.
    You can't

    You have to list every single value, and since you need the full range of int, that's gonna take some typing...
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User alex's Avatar
    Join Date
    Sep 2001
    Posts
    132
    You can't use ranges in switch... But you can do this:

    Code:
    switch((i>0)-(i<0))
    {
       case 1: printf("positive\n"); break;
       case 0: printf("zero\n"); break;
       case -1: printf("negative\n"); break;
    }
    alex

  4. #4
    Registered User
    Join Date
    Aug 2001
    Posts
    247
    I will take Alex word about switch but what you could do....

    Code:
    if ( i == 0) printf("Zero");
    else  printf("%s", i < 0 ? "Negative":"Positive");
    hoping to be certified (programming in c)
    here's the news - I'm officially certified.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How can I make this code more elegant?
    By ejohns85 in forum C++ Programming
    Replies: 3
    Last Post: 04-02-2009, 08:55 AM
  2. Format Precision & Scale
    By mattnewtoc in forum C Programming
    Replies: 1
    Last Post: 09-16-2008, 10:34 AM
  3. Intel syntax on MinGW ?
    By TmX in forum Tech Board
    Replies: 2
    Last Post: 01-06-2007, 09:44 AM
  4. opengl program as win API menu item
    By SAMSAM in forum Game Programming
    Replies: 1
    Last Post: 03-03-2003, 07:48 PM
  5. enumeration with switch case?
    By Shadow12345 in forum C++ Programming
    Replies: 17
    Last Post: 09-26-2002, 04:57 PM