How to Use When Else in VHDL: Syntax and Examples
In VHDL, the
when else statement is used for conditional signal assignment in a concise way. It assigns a value to a signal when a condition is true, otherwise assigns an alternative value. This is useful for simple if-else logic in concurrent signal assignments.Syntax
The when else statement in VHDL has this form:
signal_name <= value1 when condition else value2;
Here, signal_name is the signal to assign, value1 is assigned if condition is true, otherwise value2 is assigned.
This is a concurrent assignment, so it works outside processes.
vhdl
signal_name <= value1 when condition else value2;Example
This example shows how to assign a signal out_signal to '1' when input_signal is '1', otherwise '0'. It demonstrates simple conditional assignment using when else.
vhdl
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
entity WhenElseExample is
Port (
input_signal : in STD_LOGIC;
out_signal : out STD_LOGIC
);
end WhenElseExample;
architecture Behavioral of WhenElseExample is
begin
out_signal <= '1' when input_signal = '1' else '0';
end Behavioral;Common Pitfalls
Common mistakes when using when else include:
- Using it inside a process block (it is a concurrent statement).
- Not covering all conditions, which can cause unintended latches.
- Confusing it with
if-then-elsewhich is sequential and used inside processes.
Correct usage is outside processes for simple conditional assignments.
vhdl
-- Wrong: Using when else inside a process (not allowed) process(input_signal) begin out_signal <= '1' when input_signal = '1' else '0'; -- Error end process; -- Right: Use if-then-else inside process process(input_signal) begin if input_signal = '1' then out_signal <= '1'; else out_signal <= '0'; end if; end process;
Quick Reference
| Element | Description |
|---|---|
| signal_name | The signal to assign a value to |
| value1 | Value assigned if condition is true |
| condition | Boolean expression to test |
| value2 | Value assigned if condition is false |
Key Takeaways
Use
when else for simple concurrent conditional signal assignments in VHDL.It must be used outside processes, unlike if-then-else which is sequential inside processes.
Always ensure all conditions are covered to avoid unintended latches.
The syntax is: signal <= value1 when condition else value2;
Use if-then-else inside processes for more complex conditional logic.