Why can switch only compare to const values?

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Why can switch only compare to const values?

Kevin Peterson
Just curious:

Take a switch-statement like -

switch(myVar)
{
case(label):
...
break;
}

why label should be constant only?
_______________________________________________
help-gplusplus mailing list
[hidden email]
https://lists.gnu.org/mailman/listinfo/help-gplusplus
Reply | Threaded
Open this post in threaded view
|

Re: Why can switch only compare to const values?

Nikos Chantziaras-2
On 22/03/13 16:34, Kevin Peterson wrote:

> Just curious:
>
> Take a switch-statement like -
>
> switch(myVar)
> {
> case(label):
> ...
> break;
> }
>
> why label should be constant only?

Because it can be ambiguous otherwise:

   int a = 1, b = 1;
   int val = 1;

   switch (val) {
   case a: foo(); break;
   case b: bar(); break;
   }

Requiring constant expressions for the cases makes sure that there's no
ambiguity, since they can be evaluated at compile time.



_______________________________________________
help-gplusplus mailing list
[hidden email]
https://lists.gnu.org/mailman/listinfo/help-gplusplus