Title here
Summary here
Branching with if
and else
in VHDL is straightforward.
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
entity IfElseExample is
end IfElseExample;
architecture Behavioral of IfElseExample is
begin
process
variable num : integer := 9;
begin
-- Here's a basic example.
if (7 mod 2 = 0) then
report "7 is even";
else
report "7 is odd";
end if;
-- You can have an `if` statement without an else.
if (8 mod 4 = 0) then
report "8 is divisible by 4";
end if;
-- Logical operators like `and` and `or` are often useful in conditions.
if (8 mod 2 = 0) or (7 mod 2 = 0) then
report "either 8 or 7 are even";
end if;
-- A variable can be declared before conditionals;
-- it will be available in the current and all subsequent branches.
if (num < 0) then
report integer'image(num) & " is negative";
elsif (num < 10) then
report integer'image(num) & " has 1 digit";
else
report integer'image(num) & " has multiple digits";
end if;
wait;
end process;
end Behavioral;
Note that in VHDL, you need to use parentheses around conditions, and the then
keyword is required. The end if;
statement is used to close each if
block.
To run this VHDL code, you would typically use a VHDL simulator. The exact commands may vary depending on your development environment, but it might look something like this:
$ ghdl -a if_else_example.vhdl
$ ghdl -e if_else_example
$ ghdl -r if_else_example
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit
VHDL doesn’t have a ternary operator equivalent, so you’ll need to use a full if
statement even for basic conditions.