0
\$\begingroup\$

Is it necessary to declare reg before assignment in Verilog? Or does Verilog-2001 allow to declare reg after assignment?

For example this code is synthesized by Quartus and simulated by ModelSim without errors

module my_module(output out_my_reg);
 reg my_reg;
 assign out_my_reg = my_reg;
endmodule

And this code is synthesized by Quartus without errors but in ModelSim its simulate leds to an error Undefined variable: 'my_reg'

module my_module(output out_my_reg);
 assign out_my_reg = my_reg;
 reg my_reg;
endmodule
\$\endgroup\$
5
\$\begingroup\$

The LRM says in 1800-2017 section 6.5 Nets and variables that you must declare data(signals) before using them. There are such things as implicitly declared nets, but that does not apply here. There are also different rules when referencing names that have a . (period) in them. But both of those other situations contribute to why Verilog has this rule.

| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

TL;DR You should always declare your variables before trying to use them.


When you declare your variable first, both ModelSim and Quartus will happily know what it is. However if you try to use a variable before declaring it, all bets are off.

If you don't declare a variable at all, its existence will be inferred. Quartus usually makes them up reasonably well with a sensible width. Modelsim just makes everything as a 1-bit wire if otherwise undefined.

If you then declare the variable later in the file, this frequently causes Modelsim to error due to multiple definitions of the same variable - it's inferred one, and now your declared one. Quartus seems to be more forgiving.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.