Skip to content

Wrong answer for the challenge #3 in chapter 17 #1189

Open
@spevnev

Description

@spevnev

Your solution for conditional (ternary) operator is:

static void conditional()
{
  // Compile the then branch.
  parsePrecedence(compiler, PREC_CONDITIONAL);

  consume(compiler, TOKEN_COLON,
          "Expect ':' after then branch of conditional operator.");

  // Compile the else branch.
  parsePrecedence(compiler, PREC_ASSIGNMENT);
}

I believe it is wrong because (in C) assignment in conditional operator is allowed in the then branch but not the else branch, so the precedence of the statements should be swapped:

static void conditional()
{
  // Compile the then branch.
  parsePrecedence(compiler, PREC_ASSIGNMENT);

  consume(compiler, TOKEN_COLON,
          "Expect ':' after then branch of conditional operator.");

  // Compile the else branch.
  parsePrecedence(compiler, PREC_CONDITIONAL);
}

And since the else branch allows any expression, it may be more clear to use expression (as in grouping)?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions