Behavioral designing of a multiple input and gate

Viewed 125

I was trying to concatenate 3 2-to-1 AND gates to get a 4-to-1 AND gate using a more behavioral design. I keep getting errors, and I can't get a module to compile.

Can someone help ? (I am aware of the possibility of using y = &x, but I was trying a different method :))

module and4_gateb(x, y);
  input [3:0] x;
  reg y;
  output y;
  integer i;
  
  y = x[0];
  initial begin
    for(i=1; i<4; i= i+1) begin
      y = y&x[i];
    end
  end
endmodule

errors

1 Answers

You get those error messages because you declared y as a reg, and you need to make assignments to a reg inside a procedural block such as initial.

After I fixed that compile error, I also got a warning because you need to declare y as an output before you declare it as a reg:

module and4_gateb(x, y);
  input [3:0] x;
  output y;
  reg y;
  integer i;
  
  initial begin
    y = x[0];
    for(i=1; i<4; i= i+1) begin
      y = y&x[i];
    end
  end
endmodule

Here is a way to simplify the port declarations using ANSI-style declarations:

module and4_gateb (
  input [3:0] x,
  output reg y
);
  integer i;
  
  initial begin
    y = x[0];
    for(i=1; i<4; i= i+1) begin
      y = y&x[i];
    end
  end
endmodule

This way is less error-prone because you only need to mention each signal once (not 2 or 3 times).

Related