-1

In the following C++ program:

int opt;
in(opt);
switch(opt)
 case(opt == 1):
 //and so on…

where in(opt);is the procedure used to get the value of the integer opt.

I get the error here: case(opt == 1):

Basically the point is I want to make a way for the user to decide what feature of the program is going to be used. I also tried with a char but had no luck with it as well. I just can't figure out what's going on.

Eduardo
  • 17
  • 5
  • 3
    Instead of `case(opt == 1):`, try `case 1:`. Also, you need a curly brace after `switch(opt)` and at the end of the switch statement. Consider the examples here: https://en.cppreference.com/w/cpp/language/switch – Blaze Jan 04 '19 at 13:05
  • 1
    For learning basic C++ syntax such as this, it's better to follow a [good book](https://stackoverflow.com/q/388242/1782465) than to ask piecemeal SO questions. – Angew is no longer proud of SO Jan 04 '19 at 13:06
  • 1
    @Blaze You don't necessarily need a `{` after `switch ( )`. – melpomene Jan 04 '19 at 13:08
  • @Angew the program itself I would say it's rather complicated, it's weird I couldn't figure out this crap by myself :| Anyway thanks for the help – Eduardo Jan 04 '19 at 13:08
  • 1
    @melpomene I figured the `//and so on…` meant that there are going to be more cases than that, so I think a compound statement would help here. – Blaze Jan 04 '19 at 13:10

2 Answers2

2

The case labels in a switch block need to be compile time evaluable constant expressions (and integral types).

Since opt == 1 is only known at run-time, compilation of case (opt == 1) will fail.

Did you mean simply case 1:?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2
switch(opt) {
    case 1:
        break;
    case 2:
        break;
}

The switch part says that you're looking at the value of opt; each case statement gives a possible matching value. The value in a case statement has to be a compile-time constant.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • Requesting permission to change "compile-time constant" to "compile-time evaluable constant expression"? – Bathsheba Jan 04 '19 at 13:40
  • 1
    @Bathsheba -- that's too complicated for me. Seriously: from a language-lawyer perspective that might be correct (I haven't paid attention lately), but for beginners it's just too many words. – Pete Becker Jan 04 '19 at 13:43