VHDL coding tips and tricks: VHDL: Constants - When should you use them?

Tuesday, March 9, 2010

VHDL: Constants - When should you use them?

THIS BLOG POST WAS UPDATED ON 06-03-2024

What are constants?

In VHDL, constants resemble those found in other programming languages—they're a data class that, once declared and initialized, cannot be changed thereafter.

When a constant is declared within a VHDL entity, it must be initialized immediately. However, if declared in a VHDL package, it should be initialized either in the same statement or later in the package body. Once the code is compiled, constants stick to their assigned values. We can call them immutable.

Why would you want to use constants in your design?

If you are using certain numbers multiple times within the design, it makes sense to use a variable name for them. And that is what we call a constant. They improve readability because we can see at a glance what the value is. 
constant pi : integer := 314; -- value of pi multiplied by 100.
In the above case, the constant was even named meaningfully, which makes it even easier for someone else to understand what this number "314" means in this code without extra comments.

Constants also help with the maintainability of the design. For example, in the above code, suppose you want to increase the precision of your calculations. You can simply change the value of pi in one place instead of editing the code in multiple places.
constant pi : integer := 3141; -- value of pi multiplied by 1000.

I personally feel that constants reduce the probability of type-errors occurring.

Examples:
constant var1 : integer := 10; constant var2 : std_logic_vector(7 downto 0) := x"11"; constant var3 : std_logic := '1'; constant var4 : bit_vector(3 downto 0) := "1100"; constant var5 : real := 3.14; constant var6 : std_ulogic := '0';


No comments:

Post a Comment