1

I'm writing a code in SystemVerilog, and I'm trying to use the ternary operator to decide between two function calls. Here's my code:

module tb;
  int a = 1, b = 4;
  initial begin
    b > a ? $display("%0d", b) : $display("Value: %0d", a); // Syntax error
    $display("%0d", b > a ? b : a); // This works correctly
  end
endmodule

In the line b > a ? print(b) : print(a);, I get a syntax error, but the line print(b > a ? b : a); works perfectly. I don’t understand why using the ternary operator directly with function calls causes a syntax error.

Can someone explain why this happens and how to fix it?

1 Answer 1

1

The function calls are not the cause of the syntax error. The problem is that the ?: construct is simply an operator; it is not a complete statement by itself. You would still get a syntax error with the following code for example:

b > a ? b : a;

There are no function calls in that line. You would get the same syntax error with any operator, such as:

a || b;

To call a function based on a condition, you should use the if/else procedural code:

module tb;
  int a = 1, b = 4;
  initial begin
    if (b > a)
        $display("%0d", b);
    else
        $display("Value: %0d", a);
  end
endmodule
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.