Verilog Code for Full Adder: Syntax and Example
A full adder in Verilog can be coded using
assign statements for sum and carry outputs based on inputs a, b, and cin. The sum is a ^ b ^ cin and the carry is (a & b) | (b & cin) | (a & cin).Syntax
The full adder module has three inputs: a, b, and cin (carry in). It produces two outputs: sum and cout (carry out). The assign keyword is used to define combinational logic for these outputs.
module: Defines the module name and ports.input: Declares input signals.output: Declares output signals.assign: Defines continuous assignments for outputs.endmodule: Ends the module.
verilog
module full_adder(
input a,
input b,
input cin,
output sum,
output cout
);
assign sum = a ^ b ^ cin;
assign cout = (a & b) | (b & cin) | (a & cin);
endmoduleExample
This example shows a testbench that applies all input combinations to the full adder and prints the sum and carry outputs. It demonstrates how the full adder works for every possible input.
verilog
module test_full_adder;
reg a, b, cin;
wire sum, cout;
full_adder uut (
.a(a),
.b(b),
.cin(cin),
.sum(sum),
.cout(cout)
);
initial begin
$display("a b cin | sum cout");
for (integer i = 0; i < 8; i = i + 1) begin
{a, b, cin} = i;
#10; // wait 10 time units
$display("%b %b %b | %b %b", a, b, cin, sum, cout);
end
$finish;
end
endmodule
module full_adder(
input a,
input b,
input cin,
output sum,
output cout
);
assign sum = a ^ b ^ cin;
assign cout = (a & b) | (b & cin) | (a & cin);
endmoduleOutput
a b cin | sum cout
0 0 0 | 0 0
0 0 1 | 1 0
0 1 0 | 1 0
0 1 1 | 0 1
1 0 0 | 1 0
1 0 1 | 0 1
1 1 0 | 0 1
1 1 1 | 1 1
Common Pitfalls
Common mistakes when coding a full adder in Verilog include:
- Using
assigninside procedural blocks likealways(which is invalid). - Forgetting to include all input combinations in the carry logic, causing incorrect carry output.
- Mixing bitwise operators incorrectly (e.g., using
|instead of&for carry terms).
Always use continuous assignments for combinational logic and verify the carry expression covers all cases.
verilog
/* Wrong carry logic example */ assign cout = (a & b) | (b | cin); // Incorrect: uses OR instead of AND for second term /* Correct carry logic */ assign cout = (a & b) | (b & cin) | (a & cin);
Quick Reference
| Signal | Description |
|---|---|
| a | First input bit |
| b | Second input bit |
| cin | Carry input bit |
| sum | Sum output bit (a XOR b XOR cin) |
| cout | Carry output bit ((a AND b) OR (b AND cin) OR (a AND cin)) |
Key Takeaways
Use continuous assignments with
assign for combinational logic in Verilog full adders.Sum output is the XOR of inputs: a ^ b ^ cin.
Carry output combines all pairs of inputs with AND, then ORs them: (a & b) | (b & cin) | (a & cin).
Avoid mixing procedural and continuous assignments for the same signals.
Test all input combinations to verify correct full adder behavior.