Thread: Problem with a switch statement.

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    8

    Problem with a switch statement.

    This is a switch statement that works with a float variable. I am trying to discover why it is allowed to work. I can think of only three answers:

    1. Float isn't really float.
    2. It figures the value out within the parameters defined with round-off.
    3. The compiler is in error.

    Code:
    # include <stdio.h>
    
    int main () {
    
    float x;
    
    printf("Enter a number: ");
    scanf("%f", &x);
    
    if (x < 0)
     {
           printf("Please use a postive number.");
           return 1;
     }
    
    switch(0 <= x && x <= 10)
     {
     case 1:
           printf("OK");
           break;
     default: printf("hi"); break;
     }
    
    return 0;
    
    }
    Thanks for any help with this. It has been bothering me quite a bit.

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Your switch expression evaluates to bool -> integeral type
    Kurt

  3. #3
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Code:
    0 <= x && x <= 10
    This results in a boolean value which C treats as an integer 0 or 1. So basically your switch only operates as a if / else.

  4. #4
    Registered User
    Join Date
    Sep 2008
    Posts
    8
    Thank you very much for the quick replies and explanations.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. cin.get(); not working with my switch statement
    By tenor_jazz13 in forum C++ Programming
    Replies: 2
    Last Post: 01-12-2008, 10:33 PM
  2. having problem with string statement during a loop!
    By Hp7130p in forum C++ Programming
    Replies: 5
    Last Post: 04-21-2005, 09:40 AM
  3. Switch statement
    By big146 in forum C++ Programming
    Replies: 7
    Last Post: 06-25-2004, 07:16 AM
  4. begginner and I need help, switch statement
    By trkpony in forum C Programming
    Replies: 3
    Last Post: 04-24-2003, 08:03 AM
  5. Equivalent of less than in a switch statement?
    By Diamonds in forum C++ Programming
    Replies: 5
    Last Post: 10-14-2002, 07:14 PM