How to Use Case Statement in VHDL: Syntax and Example
In VHDL, the
case statement selects one action from many based on the value of an expression. It compares the expression against multiple choices called when branches and executes the matching branch. This helps write clear and organized conditional logic.Syntax
The case statement in VHDL evaluates an expression and executes the code under the matching when clause. Each when clause specifies a possible value or range for the expression. The others clause handles all unmatched cases.
- case expression is: starts the case statement with the expression to check.
- when value =>: defines the action for a specific value.
- when others =>: covers all other values not explicitly listed.
- end case;: ends the case statement.
vhdl
case expression is when value1 => -- statements for value1 when value2 => -- statements for value2 when others => -- statements for all other values end case;
Example
This example shows a simple VHDL process using a case statement to assign a 2-bit output based on a 2-bit input signal. It demonstrates how to select different outputs for each input value.
vhdl
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
entity case_example is
Port ( input_signal : in STD_LOGIC_VECTOR (1 downto 0);
output_signal : out STD_LOGIC_VECTOR (1 downto 0));
end case_example;
architecture Behavioral of case_example is
begin
process(input_signal)
begin
case input_signal is
when "00" =>
output_signal <= "11";
when "01" =>
output_signal <= "10";
when "10" =>
output_signal <= "01";
when others =>
output_signal <= "00";
end case;
end process;
end Behavioral;Common Pitfalls
Common mistakes when using case statements in VHDL include:
- Not covering all possible values, which causes synthesis errors unless
othersis used. - Using overlapping or invalid value ranges.
- Forgetting to end the
casestatement withend case;. - Using signals with types that are not supported by
case(e.g., real numbers).
Always include an others clause to handle unexpected values and avoid simulation mismatches.
vhdl
case input_signal is when "00" => output_signal <= "11"; -- Missing others clause causes error if input_signal is "11" end case; -- Correct way: case input_signal is when "00" => output_signal <= "11"; when others => output_signal <= "00"; end case;
Quick Reference
| Part | Description |
|---|---|
| case expression is | Start the case statement with the expression to check |
| when value => | Define action for a specific value or range |
| when others => | Catch all other values not listed |
| end case; | End the case statement |
Key Takeaways
Use
case to select actions based on discrete values of an expression.Always include a
when others clause to cover unexpected cases.The
case statement must end with end case;.Only discrete types like std_logic_vector or enumerations can be used in
case.Avoid overlapping values and ensure all possible inputs are handled.