Thread: y not float in Switch case

  1. #1
    Registered User
    Join Date
    Jul 2009

    y not float in Switch case

    why we can't use other then integer constant in case of switch?

  2. #2
    Registered User
    Join Date
    Sep 2006
    Remember that a letter is just a char, and a char is just a small integer. Also, that when you compare strings, you are returned an integer by strcmp().

    So can you have strings and still use a switch statement? Yes, sometimes - but you have to do the work around to get the integer the switch statement needs.

    Internally, I believe that a switch statement is made up into a look up table by the compiler. So every choice is basically an index into that table. Indexes can't be anything except integers.

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    New Zealand
    It was never allowable because you aren't supposed to compare floating point numbers for equality. It would never work as you'd want it to.

    Scale and round your float to an integer first and use that in your switch statement. E.g.
    float f = 1.3;
    int i = (int)(f*10+0.5);
    switch (i) {
        case 10: // 1.0
        case 13: // 1.3
        case 17: // 1.7
        case 20: // 2.0
        case 23: // 2.3
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > Internally, I believe that a switch statement is made up into a look up table by the compiler.
    It's one common approach, but not the only one.
    switch ( sparse ) {
      case 1:
      case 100000:
    You wouldn't want a lookup table if you have a large range which is sparsely populated.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Model Rocket Altitude predictor...
    By kalor_alros in forum C++ Programming
    Replies: 11
    Last Post: 09-04-2009, 12:27 AM
  2. Replies: 5
    Last Post: 03-05-2009, 11:32 AM
  3. Xmas competitions
    By Salem in forum Contests Board
    Replies: 88
    Last Post: 01-03-2004, 02:08 PM
  4. error in program????
    By SpEkTrE in forum C Programming
    Replies: 5
    Last Post: 11-24-2003, 06:16 PM
  5. A simple array question
    By frenchfry164 in forum C++ Programming
    Replies: 7
    Last Post: 11-25-2001, 04:13 PM