Switch statements limited to constants in case clauses?
On the face of it, it would be handy to be able to list a set of cases which are based on variables rather than consts. This would avoid long if-else statements and clean up some code.
However, as I understand it, switch statements are “sets” not “lists” meaning the order in which case statements are evaluated is not certain. Therefore variable based case clauses would not be safe.
Switch statements do support ranges though. E.g. “case 1..4:”. I am not sure if the compiler would object to case ranges overlapping as this would potentially lead to the situation with variable cases i.e. uncertain order of execution.
Re: Switch statements limited to constants in case clauses?
Quote:
Originally Posted by
MartinPeterBell
...Switch statements do support ranges though. E.g. “case 1..4:”.
What language supports this?
Please note that you are in Visual C++ forum.
Re: Switch statements limited to constants in case clauses?
Quote:
Originally Posted by
VladimirF
What language supports this?
Please note that you are in Visual C++ forum.
IIRC, g++ supports ranges.
Viggy
Re: Switch statements limited to constants in case clauses?
Visual Studio C++ supports ranges such as this...
switch (message)
{
case WM_INITDIALOG ... WM_COMMAND:
return (INT_PTR)TRUE;
case WM_COMMAND:
...
...
And yes I am aware that this is a Visual Studio C++ forum :-)
Re: Switch statements limited to constants in case clauses?
Quote:
Originally Posted by
MartinPeterBell
Visual Studio C++ supports ranges such as this...
Code:
switch (message)
{
case WM_INITDIALOG ... WM_COMMAND:
return (INT_PTR)TRUE;
case WM_COMMAND:
...
Which version of Visual Studio C++?
And, please, next time use Code tags while posting code snippets.
Re: Switch statements limited to constants in case clauses?
My apologies for not being clear (language used and IDE), and not using code tags :-)
The time I used cases with ranges was indeed via g++ albeit VS 2008 as the IDE.
I just tried this out on my personal laptop with Visual C++ 2010 Express IDE and standard compiler - the compilation failed. I guess this is a g++ matter and therefore outside the scope of this forum.
I guess I just didn't consider g++ and Visual C++ could possibly differ so greatly with regards to acceptable C++ syntax.
Lesson learned :-)
Re: Switch statements limited to constants in case clauses?
Quote:
Originally Posted by
MartinPeterBell
I guess I just didn't consider g++ and Visual C++ could possibly differ so greatly with regards to acceptable C++ syntax.
Lesson learned :-)
They do not differ if you use the proper ANSI command-line switches in gcc:
You will then see that gcc will fail to compile.
The issue is that by default, gcc enables extensions. Just turn them off and you get a true ANSI C++ compiler.
Regards,
Paul McKenzie
Re: Switch statements limited to constants in case clauses?
Thanks all for talking that through :-)
Best regards,
Martin