0

Possible Duplicate:
How do I select a range of values in a switch statement?

I've been getting some errors, and I've been searching for some time now, but I have no idea what is the cause of the errors. (I'm quite new to programming.)

Here are the errors I'm getting:

error: 'Essais' cannot appear in a constant-expression| (line 200)
warning: overflow in implicit constant conversion| (line 202)

I have case and cote:

  char AfficherCote (int Essais)
 {
 char Cote;
 switch (Essais)
  {
(line200)       case Essais<=20:
    {
(line 202)           Cote='Excellent';

        return (Cote);
        break;
    }
    case Essais<=40:
    {
        Cote='Très bon';
        return (Cote);
        break;
    }
    case Essais<=60:
    {
        Cote='Bon';
        return (Cote);
        break;
    }
    case Essais<=80:
    {
        Cote='Moyen';
        return (Cote);
        break;
    }
    case Essais<=100:
    {
        Cote='Muvais';
        return (Cote);
        break;
    }
    case Essais>=100:
    {
        Cote='Très mauvais';
        return (Cote);
    }
  }
}
Community
  • 1
  • 1
user1819733
  • 13
  • 1
  • 2

2 Answers2

3

switch-case only works with constant values(*) (such as 3 or 'a'), not with ranges (such as <=100). You also must not include the variable name in the case statement. Correct syntax would be as follows:

switch (Essais)
{
case 1:
   /* ... */
  break;
case 2:
   /* ... */
   break;
default:
   /* ... */
}

If you need range tests, use if instead of switch-case:

if (Essais <= 80)
  return "Cote";
else if (Essais <= 100)
  return "Muvais";

Also note that you can't use single quotation marks ' for strings. Use double quotation marks " instead, and use variables of type std::string (not char) to store strings.


(*) To be precise, the condition given in the case statements must be a constant expression of integral type, enumeration type, or class type convertible to integer or enumeration type (see §6.4.2/2 of the C++ Standard for details).

jogojapan
  • 68,383
  • 11
  • 101
  • 131
0

That's not how switch blocks work. You would need to do something like this instead:

switch (Essais) {
    case 20:
        ...
    case 40:
        ...
    case 60:
        ...
    /* etc, etc */
}

Each case compares the value in the switch statement against a specific constant value. If they are equal, that block is executed. In your code, the compiler is complaining because an expression like Essais<=20 is not a constant that it can evaluate at compile time.

Given what you are trying to do, an if ... else if ... else chain would be more appropriate. switch blocks can only test against specific values and can't handle testing ranges, which is what it appears you are trying to do.

bta
  • 43,959
  • 6
  • 69
  • 99