## Verilog Conditional Operator

Just what the heck is that question mark doing.

Have you ever come across a strange looking piece of Verilog code that has a question mark in the middle of it? A question mark in the middle of a line of code looks so bizarre; they’re supposed to go at the end of sentences! However in Verilog the ? operator is a very useful one, but it does take a bit of getting used to.

The question mark is known in Verilog as a conditional operator though in other programming languages it also is referred to as a ternary operator , an inline if , or a ternary if . It is used as a short-hand way to write a conditional expression in Verilog (rather than using if/else statements). Let’s look at how it is used:

Here, condition is the check that the code is performing. This condition might be things like, “Is the value in A greater than the value in B?” or “Is A=1?”. Depending on if this condition evaluates to true, the first expression is chosen. If the condition evaluates to false, the part after the colon is chosen. I wrote an example of this. The code below is really elegant stuff. The way I look at the question mark operator is I say to myself, “Tell me about the value in r_Check. If it’s true, then return “HI THERE” if it’s false, then return “POTATO”. You can also use the conditional operator to assign signals , as shown with the signal w_Test1 in the example below. Assigning signals with the conditional operator is useful!

## Nested Conditional Operators

There are examples in which it might be useful to combine two or more conditional operators in a single assignment. Consider the truth table below. The truth table shows a 2-input truth table. You need to know the value of both r_Sel[1] and r_Sel[0] to determine the value of the output w_Out. This could be achieved with a bunch of if-else if-else if combinations, or a case statement, but it’s much cleaner and simpler to use the conditional operator to achieve the same goal.

 r_Sel[1] r_Sel[0] Output w_Out 0 0 1 0 1 1 1 0 1 1 1 0

Learn Verilog

Save my name, email, and website in this browser for the next time I comment.

## If Statements and Case Statements in Verilog

In this post we talk about two of the most commonly used constructs in verilog - the if statement and the case statement.

We have seen in a previous post how use procedural blocks such as the always block to write verilog code which is executed sequentially .

We can also use a number of statements within procedural blocks which control the way that signals are assigned in our verilog designs. Collectively, these statements are known as sequential statements.

The case statement and the if statement are both examples of sequential statements in verilog.

In the rest of this post, we talk about how both of these statements are used in verilog. We then consider a short example for both of these constructs to show how we use them in practise.

## Verilog If Statement

The if statement is a conditional statement which uses boolean conditions to determine which blocks of verilog code to execute.

Whenever a condition evaluates as true, the code branch associated with that condition is executed.

This statement is similar to if statements used in other programming languages such as C.

The verilog code snippet below shows the basic syntax for the if statement.

We can exclude the else and else if branches from the statement if we don't need them.

In fact, we have already seen this in the post on always blocks where we used the posedge macro to detect the rising edge of a clock signal.

We can include as many else if branches as necessary to properly model the underlying circuit.

The if statement uses boolean conditions to determine which lines of code to execute.

In the snippet above, these expressions are given by <expression1> and <expression2>.

These expressions are sequentially evaluated and the code associated with the expression is executed if it evaluates to true.

Only one branch of an if statement will ever execute. This is normally the first expression which evaluates as true.

The only exception to this occurs when none of the expressions are true. In this instance, the code in the else branch will execute.

When we omit the else branch in our if statement code then none of the branches will execute in this case.

The code associated with each branch can include any valid verilog code, including further if statements. This approach is known as nested if statements.

When using this type of code in verilog, we should take care to limit the number of nested statements as it can lead to difficulties in meeting timing.

• If Statement Example

We have already seen a practical example of the if statement when modelling flip flops in the post on the verilog always block .

To demonstrate this construct more thoroughly, let's consider an example of a clocked multiplexor.

In this instance, we will use an asynchronously resettable D type flip flop to register the output of a multiplexor .

The circuit diagram below shows the circuit which we will use in this example.

The code snippet below shows how we implement this using a single always block and an if statement.

In this example, we use the first if statement to set the output of the flip flop to 0b whenever reset is active.

When the reset is not active, then the always block has been triggered by the rising edge of the clock. We use the else branch of the first if statement to capture this condition.

We use a second if statement to model the behaviour of the multiplexor circuit. This is an example of a nested if statement in verilog.

When the addr signal is 0b, we assign the output of the flip flop to input a. We use the first branch of the nested if statement to capture this condition.

We then use the else branch of the nested if statement to capture the case when the addr signal is 1b.

It is also possible for us to use an else-if type statement here but the else statement is more succinct. The behaviour is the same in both cases as the signal can only ever be 0b or 1b in a real circuit.

## Verilog Case Statement

We use the verilog case statement to select a block of code to execute based on the value of a given signal in our design.

When we write a case statement in verilog we specify an input signal to monitor and evaluate.

The value of this signal is then compared with the values specified in each branch of the case statement.

Once a match is found for the input signal value, the branch associated with that value will execute.

The verilog case statement performs the same function as the switch statement in the C programming language.

The code snippet below shows the general syntax for the case statement in verilog.

It is possible to exclude the default branch of the statement, although this is not advisable. If the default branch is excluded then all valid values of the <variable> must have it's own branch.

As with the if statement, the code associated with each branch can include any valid verilog code.

This includes further sequential statements, such as if or case statements. Again, we should try to limit the number of nested statements as it makes it easier to meet our timing requirements.

• Case Statement Example

To better demonstrate the way we use the case statement in verilog, let's consider a basic example.

For this example we will look at a simple four to one multiplexor circuit.

We frequently use the case statement to model large multiplexors in verilog as it produces more readable code than continuous assignment based implementations.

The code snippet below shows how we would implement this circuit using a case statement.

This example shows how simple it is to model a multiplexor using the case statement in verilog. In fact, the case statement provides the most intuitive way of modelling a multiplexor in verilog.

Although this example is quite straight forward, there are a few important points which we should consider in more detail.

The first thing to note in this example is that we use blocking assignment . The reason for this is that we are modelling combinational logic and non-blocking assignment normally leads to flip flops being placed in our design.

Another thing to note here is that we could remove the default keyword from this example. We would then explicitly list the value of addr required to output the value of d instead.

However, we have included the default keyword in this example to demonstrate how it should be used.

Which blocks do we use to write sequential statements in a verilog design?

Sequential statements can only be written within a procedural block such as an always block or initial block.

Which keywords can we exclude from the if statement when they are not required?

We can exclude the else and else if keywords if they are not needed.

How many branches of the if statement can be executed at one time?

A maximum of one branch in an if statement can execute at any time.

When can we exclude the default branch from the case statement?

We can exclude the default branch if all valid values of the input signal are explicitly listed.

Use a case statement to write the code for a six to one multiplexor.

Rewrite the six to one multiplexor from the last exercise so that it uses an if statement.

## One comment on “If Statements and Case Statements in Verilog”

clearly explained with nice examples the style of the web page is also nice

Save my name, email, and website in this browser for the next time I comment.

Don't Miss Out

## Global training solutions for engineers creating the world's electronics

Full Training Programs

• Course Calendar
• Formal Verification
• SystemVerilog & UVM
• SystemC & TLM-2.0 Training
• Verification Methodology
• AI & Machine Learning
• Digital Design
• C/C++ for Embedded
• Linux & Yocto
• Verilog & SystemVerilog
• FPGA & ASIC Design using VHDL
• Signal Integrity

Free Online Training Events

• Meeting the Challenge of OTA for Embedded Linux Systems
• Developments in Accelerated Adaptable Technology
• How to Improve Embedded Software using State Machines
• When to use Helper Code to Accelerate Formal
• On Demand Webinars Available Now

Free Technical Resources

• Embedded / Arm
• Video Gallery
• KnowHow FAQs
• SystemC & TLM-2.0
• Deep Learning
• Embedded C/C++
• Linux/Yocto
• Intel (Altera)
• When to use Helper Code to Accelerate Formal Analysis
• News, PR & Events
• Reference Guides
• Booking Terms & Conditions

## KnowHow Free Technical Resources

Find a training course, if statement.

In the last section, we looked at describing hardware conceptually using always blocks. What kind of hardware can we describe? What are the limitations? What kinds of Verilog statement can be used in always blocks to describe hardware? Well, we have already seen the use of an if statement to describe a multiplexer, so let's dwell on if statements in this section.

The code snippet above outlines a way to describe combinational logic using always blocks. To model a multiplexer, an if statement was used to describe the functionality. In addition, all of the inputs to the multiplexer were specified in the sensitivity list.

## Variable declaration

It is a fundamental rule of the Verilog HDL that any object that is assigned a value in an always statement must be declared as a variable. Hence,

The term variable was introduced in the verilog-2001 standard. Previously, the term used was register . This was confusing, because a Verilog variable (register) does not necessarily imply that a hardware register would be synthesised, hence the change of terminology.

## Combinational logic

It transpires that in order to create Verilog code that can be input to a synthesis tool for the synthesis of combinational logic, the requirement for all inputs to the hardware to appear in the sensitivity list is a golden rule.

Golden Rule 1:

To synthesize combinational logic using an always block, all inputs to the design must appear in the sensitivity list.

Altogether there are 3 golden rules for synthesizing combinational logic, we will address each of these golden rules over the next couple of sections in this tutorial.

The if statement in Verilog is a sequential statement that conditionally executes other sequential statements, depending upon the value of some condition. An if statement may optionally contain an else part, executed if the condition is false. Although the else part is optional, for the time being, we will code up if statements with a corresponding else rather than simple if statements. In order to have more than one sequential statement executed in an if statement, multiple statements are bracketed together using the begin..end keywords,

If statements can be nested if you have more complex behaviour to describe:

Notice that the code is beginning to look a little bit confusing! In the code above, begin..end blocks have only been used where they must be used, that is, where we have multiple statements. It is probably a good idea to use begin..end blocks throughout your Verilog code - you end up typing in a bit more Verilog but it's easier to read. Also, if you have to add more functionality to an always block later on (more sequential statement), at least the begin..end block is already in place. So,

Note that the order of assignments to f , g and h has been played around with (just to keep you on your toes!).

## Synthesis considerations

If statements are synthesized by generating a multiplexer for each variable assigned within the if statement. The select input on each mux is driven by logic determined by the if condition, and the data inputs are determined by the expressions on the right hand sides of the assignments. During subsequent optimization by a synthesis tool, the multiplexer architecture may be changed to a structure using and-or-invert gates as surrounding functionality such as the a & b and the ~a can be merged into complex and-or-invert gates to yield a more compact hardware implementation.

## Free Online Training

Find out about our upcoming events, related training.

• Comprehensive Verilog
• Comprehensive Verilog Online

## Henry Hastings

Lockheed martin.

View more references

## Verilog Assignments

Variable declaration assignment, net declaration assignment, assign deassign, force release.

• Procedural continuous

## Legal LHS values

An assignment has two parts - right-hand side (RHS) and left-hand side (LHS) with an equal symbol (=) or a less than-equal symbol (<=) in between.

Assignment typeLeft-hand side
Procedural
Continuous
Procedural Continous

The RHS can contain any expression that evaluates to a final value while the LHS indicates a net or a variable to which the value in RHS is being assigned.

## Procedural Assignment

Procedural assignments occur within procedures such as always , initial , task and functions and are used to place values onto variables. The variable will hold the value until the next assignment to the same variable.

The value will be placed onto the variable when the simulation executes this statement at some point during simulation time. This can be controlled and modified the way we want by the use of control flow statements such as if-else-if , case statement and looping mechanisms.

An initial value can be placed onto a variable at the time of its declaration as shown next. The assignment does not have a duration and holds the value until the next assignment to the same variable happens. Note that variable declaration assignments to an array are not allowed.

If the variable is initialized during declaration and at time 0 in an initial block as shown below, the order of evaluation is not guaranteed, and hence can have either 8'h05 or 8'hee.

Procedural blocks and assignments will be covered in more detail in a later section.

## Continuous Assignment

This is used to assign values onto scalar and vector nets and happens whenever there is a change in the RHS. It provides a way to model combinational logic without specifying an interconnection of gates and makes it easier to drive the net with logical expressions.

Whenever b or c changes its value, then the whole expression in RHS will be evaluated and a will be updated with the new value.

This allows us to place a continuous assignment on the same statement that declares the net. Note that because a net can be declared only once, only one declaration assignment is possible for a net.

## Procedural Continuous Assignment

• assign ... deassign
• force ... release

This will override all procedural assignments to a variable and is deactivated by using the same signal with deassign . The value of the variable will remain same until the variable gets a new value through a procedural or procedural continuous assignment. The LHS of an assign statement cannot be a bit-select, part-select or an array reference but can be a variable or a concatenation of variables.

These are similar to the assign - deassign statements but can also be applied to nets and variables. The LHS can be a bit-select of a net, part-select of a net, variable or a net but cannot be the reference to an array and bit/part select of a variable. The force statment will override all other assignments made to the variable until it is released using the release keyword.

## Assign Statement In Verilog

• You can use assign statement inside of module.
• You can use assign statement to output port and any wire declared inside the module

## Examples of assign statement

In above example, y is output port and we are assigning this output port to a and b. It will create a and gate where a and b are inputs and y is output

In above example, we've descrived a NAND gate. We can use one statemetn but for better understanding we've use two statement to illustrate how we can use assign statement to both wire and output port. wire w is assign with a AND b, and output y is assigned not of wire w. This creates a NAND gate in verilog HDL.

In above example, we have described a full-adder using assign statement. Note that we can write complete boolean equation using assign statement

We can also use Verilog operators using assign statement. Below is the example of full-adder using assign statement and Verilog operator

In above example, we are using + operator, which addition operator in Verilog. We are assigning output sum and carry with addition of a, b and cin.

Click like if you found this useful

This policy contains information about your privacy. By posting, you are declaring that you understand this policy:

• Your name, rating, website address, town, country, state and comment will be publicly displayed if entered.
• The time/date of your submission (displayed)
• Administrative purposes, should a need to contact you arise.
• A cookie may be set on your computer. This is used to remember your inputs. It will expire by itself.

This policy is subject to change at any time and without notice.

These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:

• Although the administrator will attempt to moderate comments, it is impossible for every comment to have been moderated at any given time.
• You acknowledge that all comments express the views and opinions of the original author and not those of the administrator.
• You agree not to post any material which is knowingly false, obscene, hateful, threatening, harassing or invasive of a person's privacy.
• The administrator has the right to edit, move or remove any comment for any reason and without notice.

Failure to comply with these rules may result in being banned from submitting further comments.

These terms and conditions are subject to change at any time and without notice.

• Search forums

Follow along with the video below to see how to install our site as a web app on your home screen.

Note: This feature may not be available in some browsers.

## Welcome to EDAboard.com

Welcome to our site edaboard.com is an international electronics discussion forum focused on eda software, circuits, schematics, books, theory, papers, asic, pld, 8051, dsp, network, rf, analog design, pcb, service manuals... and a whole lot more to participate you need to register. registration is free. click here to register now..

• Digital Design and Embedded Programming
• PLD, SPLD, GAL, CPLD, FPGA Design

## How to use 2 condition in assign [verilog]

• Start date Oct 17, 2012
• Oct 17, 2012

## Newbie level 6

always_comb //always_comb is the same function as assign begin if(a==b) z=a; else if (b==c) z=b; end Click to expand...
assign z = (a & b) ? a:z; //I know thats wrong since a=/=b , this will output z for z. What should I write if a=/=b, it will do " if (b==c) z=b; Click to expand...

Your always_comb blocks is not combinatorial - if a != b, and b != c, then there is no assignment to z and you have a latch. Your second if statement needs an else clause. In any case, the conditional ?: operator can be nested: assign z = (a==b) ? a : (b==c) ? b : z; That z at the end represents the missing else clause.

## Full Member level 6

 Code Verilog - ] @ * begin   if (a==b)       z = a;   else if (b==c) z = b end
 Code Verilog - ] z = a==b ? a : b==c ? b;

always_comb is the same function as assign Click to expand...
 Code Verilog - ] @* //always, just like always_comb functionally speaking is somewhere in the same galaxy as assign. sometimes. begin     if(a==b)         z=a;     else         if (b==c)             z=b; end
if(a==b) begin z=a; count=count+1; end else if (b==c) begin z=b; count=count+2; end Click to expand...
assign z = (a==b) ? (a & (count=count+1)) : (b==c) ?( b & (count=count+2)): z; Click to expand...

daisordan, If you want your code to be synthesizable, you cannot combine combinatorial and sequential logic like this in a single assign statement. You will need to explain your desired functionality without using any Verilog syntax first so we can suggest the best way to code what you want to achieve. If you don't care if your code is synthesizable, you can assign the output of a function call Code: assign z = myfunction(a,b,c); function logic myfunction(input a,b,c); if(a==b) begin z=a; count=count+1; // this is a side-effect that is not synthesizable end else if (b==c) begin z=b; count=count+2; // this is a side-effect that is not synthesizable end endfunction The biggest difference between always_comb and an assign statement is with the how the simulator deals with the semantics of function calls. An assignment statement only looks for events on the operands that appear on the RHS of the assignment, while always_comb expands functions in-line and looks for any change of any operand that appears inside the function. For example suppose I re-wrote the function to directly reference a,b,c instead of passing them as arguments to the function: Code: assign z1 = myfunction(); always_comb z2 = myfunction(); function logic myfunction(); if(a==b) z=a; else if (b==c) z=b; else z ='bx; // a don't care to prevent a latch endfunction The asssign z1= statement would never execute because there are no triggering events on the RHS to cause an evaluation. The always_comb z2= block executes at time 0, and when there is a change on any operand that is referenced within the block. mrfibble, I recommend NEVER TO USE always @(*) because it does not guarantee execution at time 0. I have Seen code like Code: real pi; `define PI 3.14159 always @(*) pi = `PI; // DO NOT EVER DO use always_comb pi = `PI; instead that fails because there was never an event to trigger the always @(*) block.

daisordan said: mrflibble: Could you briefly talk about why always_comb and assign are different? because when I read some verilog beginner's book, it said that are doing the same things. Click to expand...
dave_59 said: mrfibble, I recommend NEVER TO USE always @(*) because it does not guarantee execution at time 0. I have Seen code like Code: real pi; `define PI 3.14159 always @(*) pi = `PI; // DO NOT EVER DO use always_comb pi = `PI; instead that fails because there was never an event to trigger the always @(*) block. Click to expand...

• Started by mahesh_namboodiri
• Jan 31, 2024
• Started by keikaku
• Mar 5, 2024
• Replies: 10
• Started by combat5
• May 28, 2024
• Started by hudda
• May 25, 2024
• Started by alexis57
• Jan 28, 2024

## Part and Inventory Search

Welcome to edaboard.com.

• This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register. By continuing to use this site, you are consenting to our use of cookies. Accept Learn more…
• Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
• OverflowAI GenAI features for Teams
• OverflowAPI Train & fine-tune LLMs
• Labs The future of collective knowledge sharing
• About the company Visit the blog

## Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

## Verilog question mark (?) operator

I'm trying to translate a Verilog program into VHDL and have stumbled across a statement where a question mark ( ? ) operator is used in the Verilog program.

The following is the Verilog code;

I don't understand the 8th line, could anyone please shed some light on this? I've read on the asic-world website that the question mark is the Verilog alternate for the Z character. But I don't understand why it's being used in this context.

Kind regards

That's a ternary operator . It's shorthand for an if statement

Translates to something like (not correct syntax but I think you'll get it):

Here are two examples of a 2 to 1 MUX using if statement and ternary operator .

On the asic-world website, it is covered under Conditional Operators

• What if tone[23] is X or Z? –  PieterNuyts Commented Mar 20, 2023 at 11:10

Another way of writing, e.g. the following Verilog:

in VHDL would be:

• This is why declarations are so essential in questions. A condition must evaluate to a boolean value. The only way tone[23] will meet that criteria is if tone is a BOOLEAN_VECTOR. –  user1155120 Commented Jan 7, 2016 at 4:52
• @user1155120 Not so. In VHDL-2008 it is allowed to be a boolean, std_logic, or bit. –  Jim Lewis Commented Aug 23, 2018 at 3:07
• The condition operator (9.2.9) which can be applied implicitly (after the when in a conditional assignment statement) is predefined in package standard for type BIT. Absent declarations (or an entity header) the type type of tone is not known. Note the overload condition operator is defined for type std_ulogic in package std_logic_1164 (and would cover elements of the various array types with an element base type of std_ulogic). There's nothing from preventing you providing your own overloaded operator, it converts an element type to a BOOLEAN. –  user1155120 Commented Aug 23, 2018 at 3:52
• A hurried survey apparently shows no synthesis vendors supporting the condition operator implicit or otherwise. –  user1155120 Commented Aug 23, 2018 at 15:10
• Oops! shows up in the Synopsys FPGA Synthesis Synplify Pro for Microsemi Edition Reference Manual October 2011. Page 752, both implicit and explict condition operators. There may be earlier references. –  user1155120 Commented Aug 24, 2018 at 4:54

Think of it as a MUX, before the ? is the selection bit and on two sides of : are the inputs

• Please be more specific. –  Abhishek Dutt Commented Mar 22, 2021 at 7:29
• More specific about Mux or the question mark? After knowing it's a MUX it should be enough to translate to VHDL, assuming you understand hardware and vhdl. –  DavidYu Commented Apr 14, 2021 at 5:41

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

• Featured on Meta
• We spent a sprint addressing your requests — here’s how it went
• Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
• What makes a homepage useful for logged-in users

## Hot Network Questions

• Alternatives to iterrow loops in python pandas dataframes
• Real-life problems involving solving triangles
• Why does Macbeth well deserve his name?
• The rear wheel from my new Road Bike vibrates strongly
• Decomposing the homology of a finite-index subgroup into isotypic components
• Coincidence between coefficients of tanh(tan(x/2)) and Chow ring computations?
• Mtu and mss concept
• Canon PowerShot A80 keeps shutting down and asking to change the battery pack. What should I do?
• Fill the grid subject to product, sum and knight move constraints
• Why do jet aircraft need chocks when they have parking brakes?
• I want to pick my flight route. I can either get 2 round trip tickets (SRC<->MID, MID<->DST) or 3rd party booking (SRC<->DST). Which is more reliable?
• Can I set QGIS to summarize icons above a certain scale and display only the number of icons in an area?
• How are Boggarts created?
• Big zeros in block diagonal matrix
• Why does black have a higher win rate on Lichess in Exchange French?
• Can trills have 3 notes instead of two?
• Are you radical enough to solve this SURDOKU?
• How can I get the value of the f(1/2) is 11/4 not 2.75 when I use \pgfmathprintnumber\pgfmathresult?
• Identify the story about an author whose work-in-progress is completed by a computer
• Is taping behind tile necessary when drywall seams are not easily accessible?
• Sci fi book that has a tunnel. Depending on where you go through wall, go to different planet
• What type of airfoil should be used for horizontal tailplanes?
• Quantum: why linear combination of vectors (superposition) is described as "both at the same time"?

## Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

## verilog module inside an if-statement

I have to build a circuit of an arithmetic right shift operator in verilog and include it in a verilog code of a simple computer. I've written the code of the circuit with a module and it compiles without an error but when I try to include it in the code of the computer(it has to be in an if-statement) an error occurs: "error: syntax error, unexpected MODULE" is it possible to include a module in an if-statement?

this is a piece of the code: the comment is the old piece of code where right shift is done everything beneath are the changes i've done. I did not comment the whole code because it is very big

• \\$\begingroup\\$ You are describing hardware, not writing software. Modules are hardware, you can't instantiate them conditionally with if statements (*). \\$\endgroup\\$ –  Tom Carpenter Commented May 9, 2017 at 16:25
• 2 \\$\begingroup\\$ Think about what it would describe. If a signal is high, make some hardware appear, otherwise delete the hardware. FPGAs can't work like that. All hardware is described and fixed at synthesis. \\$\endgroup\\$ –  Tom Carpenter Commented May 9, 2017 at 16:26
• \\$\begingroup\\$ You could make your right shift code a function, in which case you can call it like the commented out line. This would infer the hardware always being there, but it's output feeds an implicit multiplexer. \\$\endgroup\\$ –  Tom Carpenter Commented May 9, 2017 at 16:28
• \\$\begingroup\\$ Alternatively instantiate your module not in an if statement, connect its output to a wire, and then use that wire in the if statement. This is basically what a function would infer. \\$\endgroup\\$ –  Tom Carpenter Commented May 9, 2017 at 16:30
• \\$\begingroup\\$ I'll convert all my comments to a proper answer when I get home. On my phone at the moment. \\$\endgroup\\$ –  Tom Carpenter Commented May 9, 2017 at 16:31

It is important to remember that with Verilog you are describing hardware, not writing software. Modules are instances of hardware. They can't be called and they don't return a value.

You can't instantiate a module conditionally within an if statements (*), and you definitely can't instantiate them within procedural blocks. If you consider what such a statement would describe it becomes clear as to why not. With a module instantiation within an if statement you are basically saying:

If signal is high, make some hardware appear; otherwise delete the hardware.

FPGAs can't work like that. All hardware is described and fixed at synthesis.

Instead what you need to do is instantiate your hardware (in this case right shift module) not within the if statement or procedural block. Connect the output of that module to a wire. Now your hardware is always present, regardless of the control signals. So how do you make use of it conditionally?

This is quite simple. Within the if statement you can use your wire. If a condition is met assign the wire to whatever signal you are controlling. Otherwise assign some other signal.

The reason this now works is because rather than trying to infer transient hardware, you are now inferring a simple multiplexer. The inputs to the multiplexer are the module_output_wire and something_else , the select signal is some_condition , and the output of the multiplexer is some_signal . The hardware always exists, but you don't always need to use the output value.

As an alternative, you could make your right shift code a function. A function in Verilog can be called in the way you show on the commented out line in your code. In the case of the function you are inferring hardware that is always there and the output of the hardware is a wire (the return value of the function) which you can then use in an always block.

(*) With the exception of in Verilog 2001 Generate statements, but in that case the condition is known at compile time, it doesn't depend on the value of a signal.

Use mulitplexers to select different busses (or op codes), all hardware you are using needs to be there when you compile, FPGA's can't change their hardware on the fly (yet).

If you really want to select between different hardware modules then you can use the equivalent of a #define in C to select what hardware gets compiled. But the selection can only happen before compiling.

conditional_compilation_directive ::= ifdef_directive | ifndef_directive ifdef_directive ::= `ifdef text_macro_identifier ifdef_group_of_lines { `elsif text_macro_identifier elsif_group_of_lines } [ `else else_group_of_lines ] `endif ifndef_directive ::= `ifndef text_macro_identifier ifndef_group_of_lines { `elsif text_macro_identifier elsif_group_of_lines } [ `else else_group_of_lines ] `endif

Required, but never shown

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

• Featured on Meta
• Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
• We spent a sprint addressing your requests — here’s how it went

## Hot Network Questions

• 8x8 grid with no unmarked L-pentomino
• Citation hunting: Floer on spectral sequences
• Are you radical enough to solve this SURDOKU?
• Is it possible with modern-day technology to expand an already built bunker further below without the risk of collapsing the entire bunker?
• Is it possible to replace the flat-top pins on flat pedals with ones that have a dome top?
• Can I reuse a large part of my own previously published paper in a new paper?
• Why does black have a higher win rate on Lichess in Exchange French?
• Does the cosmological constant entail a mass for the graviton?
• Is this a Hadamard matrix?
• Big zeros in block diagonal matrix
• Keyboard Ping Pong
• Am i interpreting title fraud statistics correctly?
• Error concerning projectile motion in respected textbook?
• When, if ever, is bribery legal?
• Largest possible relative error
• Is it alright to display mean CPU usage of algorithm instead of CPU cores available?
• Real-life problems involving solving triangles
• Eliminating "implicit conversion changes signedness" warning using _Generic
• Is it a security issue to expose PII on any publically accessible URL?
• Submitting 2 manuscripts explaining the same scientific fact but by two different methods
• Are there countries where only voters affected by a given policy get to vote on it?
• DHCP assigned addresses following devices/users and routing
• Animate multiple material transitions smoothly

#### IMAGES

1. PPT

2. Verilog IF ELSE statements

3. Verilog if-else-if

4. PPT

5. Use Verilog to Describe a Combinational Circuit: The “If” and “Case

6. Verilog If Else

#### VIDEO

1. Lecture : 11 Implementing If Else Statement using Verilog

2. meaning of statement, expression in verilog

3. Conditional Generate Statement

4. wait statement usage in verilog

5. Assign statements || Verilog lectures in Telugu

6. Arithmetic Circuits in Verilog, Part 2

1. If statement and assigning wires in Verilog

The assign statement serves as a conditional block like an if statement you are probably used to in popular programming languages such as C or C++. The assign operator works as such: Assign my value to other values based upon if certain conditions are true. The above assign operator works as follows: If val == 2'b00, assign x to the value of a.

2. Verilog Conditional Statements

In Verilog, conditional statements are used to control the flow of execution based on certain conditions. There are several types of conditional statements in Verilog listed below. Conditional Operator <variable> = <condition> ? <expression_1> : <expression_2>; The conditional operator allows you to assign a value to a variable based on a ...

3. Conditional Operator

The question mark is known in Verilog as a conditional operator though in other programming languages it also is referred to as a ternary operator, an inline if, or a ternary if. It is used as a short-hand way to write a conditional expression in Verilog (rather than using if/else statements). Let's look at how it is used:

4. Verilog if-else-if

Verilog if-else-if. This conditional statement is used to make a decision on whether the statements within the if block should be executed or not. If there is an else statement and expression is false then statements within the else block will be executed.

5. system verilog

I believe the issue is with your order of operation. always_comb blocks execute procedurally, top to bottom. In simulation, Z is updated first with the existing value of Result (from the previous time the always block was executed). The Result is updated and Z is not re-evaluated.Result is not part of the sensitivity list because it is a left-hand value. . Therefore, Z will not get updated ...

6. Verilog assign statement

Verilog assign statement. Signals of type wire or a similar wire like data type requires the continuous assignment of a value. For example, consider an electrical wire used to connect pieces on a breadboard. As long as the +5V battery is applied to one end of the wire, the component connected to the other end of the wire will get the required ...

7. verilog

Verilog assign breaks the synthesis using Icestorm. 2. Verilog if-else-if syntax. 0. Synthesis of Blocking Statements in Verilog - time required for circuit to complete. 1. What value will be assigned to x, is it a or ~x? Hot Network Questions Is it unfair to retroactively excuse a student for absences?

8. If Statements and Case Statements in Verilog

Verilog If Statement. The if statement is a conditional statement which uses boolean conditions to determine which blocks of verilog code to execute. Whenever a condition evaluates as true, the code branch associated with that condition is executed. This statement is similar to if statements used in other programming languages such as C.

9. If statement

If statement. The if statement in Verilog is a sequential statement that conditionally executes other sequential statements, depending upon the value of some condition. An if statement may optionally contain an else part, executed if the condition is false. Although the else part is optional, for the time being, we will code up if statements ...

10. if statement in Verilog

if statement in Verilog. Verilog supports 'if', 'else if', 'else' same as other programming languages. The 'If' statement is a conditional statement based on which decision is made whether to execute lines inside if block or not. The begin and end are required in case of multiple lines present in 'if' block. For single-line ...

11. Verilog conditional assignments without using procedural blocks like

Both examples were taken from the link I shared before, my QUESTION IS if there is something in Verilog, similar to VHDL using the with/select, that is easy to understand without using procedural blocks?. The first verilog example does the job but it takes a bit to understand the logic.

12. How does an "if" statement and "always@" statement work in Verilog?

The assign statement updates as soon as the for loop ends. So, if a write to the BUS is registered, the program exits the for loop but quickly re-enters it after the BUS is updated with data. The program becomes an endless cycle in which the for loop changes the data in the BUS and because the BUS is changed it executes itself all over again.

13. Verilog Assignments

reg q; initial begin assign q = 0; #10 deassign q; end force release. These are similar to the assign - deassign statements but can also be applied to nets and variables. The LHS can be a bit-select of a net, part-select of a net, variable or a net but cannot be the reference to an array and bit/part select of a variable.

14. Assign Statement In Verilog

assign keyword is used to assign ouput port or wire some digital logic. This keyword is the part of dataflow modeling in Verilog. In this post, we will see how to use this keyword in your Verilog code. You can use assign statement inside of module. You can use assign statement to output port and any wire declared inside the module.

15. Verilog Non-Blocking And IF-Statement

Non-blocking statements in Verilog work in the following fashion: The expressions on the right-hand side get evaluated sequentially but they do not get assigned immediately. The assignment takes place at the end of the time step. In your example, clk_counter + 1 is evaluated but not assigned to clk_counter right away.

16. How to use 2 condition in assign [verilog]

The biggest difference between always_comb and an assign statement is with the how the simulator deals with the semantics of function calls. An assignment statement only looks for events on the operands that appear on the RHS of the assignment, while always_comb expands functions in-line and looks for any change of any operand that appears inside the function.

17. if statement

Wire3 is a wire variable defined to retrieve the output from the Case3 module for further usage. It's hard to know even where to start here but I'd recommend going back to your textbook and reviewing 1) Usage of Verilog primitives (your 'or' there) 2) Usage of assign statements 3) always blocks.

18. vhdl

In VHDL-2008 it is allowed to be a boolean, std_logic, or bit. The condition operator (9.2.9) which can be applied implicitly (after the when in a conditional assignment statement) is predefined in package standard for type BIT. Absent declarations (or an entity header) the type type of tone is not known.

19. verilog module inside an if-statement

begin. module right_shift (alu_A,alu_B,alu); input [15:0] alu_A; input [3:0] alu_B; output [15:0] alu; this is a piece of the code: the comment is the old piece of code where right shift is done everything beneath are the changes i've done. I did not comment the whole code because it is very big. verilog. Share.