You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Verilog模块中output端口能否作为assign语句的输入?

Verilog端口作为assign输入的疑问解答

问题背景

我正在学习Verilog,在HDLBits平台上完成练习题时,自己的正确解答和参考答案写法不同,产生了技术疑问:

为什么参考答案中可以将output类型端口作为assign语句的输入?该端口并非reg类型,同时我也不清楚reg类型的output端口是否支持这种用法。

我的正确代码

module top_module(
    input a,
    input b,
    input c,
    input d,
    output out,
    output out_n   ); 
    
    wire and_ab;
    wire and_cd;
    wire or_out;
    and(and_ab,a,b);
    and(and_cd, c, d);
    or(or_out, and_ab, and_cd);
    assign out= or_out;
    not(out_n,or_out);
endmodule

参考答案代码

module top_module (
    input a,
    input b,
    input c,
    input d,
    output out,
    output out_n );
    
    wire w1, w2;        // Declare two wires (named w1 and w2)
    assign w1 = a&b;    // First AND gate
    assign w2 = c&d;    // Second AND gate
    assign out = w1|w2; // OR gate: Feeds both 'out' and the NOT gate

    assign out_n = ~out;    // NOT gate
    
endmodule

疑问解析

1. 为什么output端口(默认wire类型)可以作为assign输入

Verilog中,未显式声明类型的output端口默认是wire类型。而wire的本质是连线型数据,它的特性就是既可以被驱动(作为assign语句的左值),也可以被读取(作为assign语句的右值)——这和它是否是模块端口无关。

在参考答案里,out先被assign out = w1|w2;驱动,此时out就成为了一个带有确定逻辑值的wire,自然可以被后续的assign out_n = ~out;读取,作为反向逻辑的输入。

2. reg类型的output端口是否支持这种用法

答案是肯定的。如果output被声明为reg类型(如output reg out;),只要该reg已经被正确赋值(通常在always块中完成),它的当前值就可以被读取,作为assign语句或其他逻辑块的输入。

举个合法的示例:

module test(
    input clk,
    input a,
    output reg out,
    output out_n
);
always @(posedge clk) begin
    out <= a; // 在时钟上升沿给reg类型的out赋值
end
assign out_n = ~out; // 读取reg类型的out作为assign输入
endmodule

这段代码可以正常综合,对应硬件是一个触发器加一个反向器,完全符合语法和综合规则。

总结

  • 默认output端口为wire类型,wire支持被驱动和读取,因此可作为assign语句的输入;
  • reg类型的output端口,只要已通过always块等方式完成赋值,同样可以被读取作为assign语句的输入。

内容的提问来源于stack exchange,提问作者WoWPro71

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 15:45:30