Wire assignment inside IF block

Viewed 63

I'm having trouble assigning a value to a wire inside an if block. I would have thought this would be fairly straight forward, but the error I'm getting is:

near "assign": syntax error, unexpected assign, expecting IDENTIFIER or TYPE_IDENTIFIER or NETTYPE_IDENTIFIER.

This is my module code:

module fulladder(input logic S, a, b, cin,
                 output logic s, cout);
  
  wire b_;
  
  assign b_ = b;
  always_comb
  begin
    if (S) begin:
      assign b_ = ~b;
    end
  end

  wire p, g;
  assign p = a ^ b;
  assign g = a & b;
  assign s = p ^ cin;
  assign cout = g | (p & cin);
endmodule

I'm trying to invert b if S=1 (convert A + B into A - B using 2's-complement).

Is this approach workable? Can anyone see what I'm doing wrong?

2 Answers

You can model this behavior with a mux, and a common way to do that is to use the conditional operator:

module fulladder(input logic S, a, b, cin,
                 output logic s, cout);
  
  wire b_ = (S) ? ~b : b;
  
  wire p, g;
  assign p = a ^ b;
  assign g = a & b;
  assign s = p ^ cin;
  assign cout = g | (p & cin);
endmodule

This fixes all compile errors.


The specific error message you get is due to the colon after the begin keyword (begin:). When you use a colon there, it must be followed by a block name identifier, but it is followed by another keyword (assign) which is on the next line. You either meant to give the block a unique name (which is optional), or the colon is a typo.

Even if the colon is removed, you should not use an assign keyword inside any type of always block. Also, you should not make assignments to a signal with both a continuous assignment (your 1st assign statement) and from within an always block.

If you want to use the same way of writing (assignment, then override if condition S is found), I would do it like this:

    logic b_;
    always_comb begin
        b_ = b;
        if (S) begin
            b_ = ~b;
        end
    end

I opted for this solution since it is similar to the original code, and in the title it was explicitly asked to include assignment inside an IF block, even though probably the ternary operator shown by @toolic is the cleaner solution.

Please also notice that in the following part of your code b_ is not used anywhere yet, so our solutions are pointless so far.

Related