Search code examples
c++conditional-operator

Ternary operator vs VSCode "expected expression error"


I tried to change simple if/else statement into ternary but after typing it as:

cout << endl
         << "1. Another equation" << endl
         << "2. Exit Calculator" << endl;
    int afterCalc;
    cin >> afterCalc;

    (afterCalc == 1)? goto calcStart : continue;

I get "expected expression" notice and code doesnt debug/compile. Is there sth wrong with the code or it's VSC bug?


Solution

  • The conditional operator requires expressions as its operands. goto and continue are statements and not expressions, so the operator can't work with any of them.

    Statements are instructions for the program - "what to do"; they usually end with a semicolon ; or a closing brace }.

    Expressions are fragments of code whose value should be used — in other expressions or in statements. It doesn't make sense to use flow control instructions in an expression.

    See cppreference for more info.


    You should make code readable, as a general guideline. This is even more important if you really must use goto and continue — these rare cases are when the code does some obscure and important stuff, and you should try to use the most readable way to express your code! That is, leave it as if-statement, and maybe add comments to explain what your code does.

    Alternatively, rewrite your code so that it doesn't use goto.