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?
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