Wait a sec... the question is asking about conditional instantiation of two different instances of moduleex: s1 or s2. Conditional instantiation is a compile-time option, not a procedural like ‘if’. Conditional instantiation is something you do with `ifdef or genvar - only once, when the logic is compiled.
Unfortunately, hardware being what it is, to model what is being asked - selecting between one instance and another - you have no choice but to create both instance s1 and s2 before the ‘if’ statement, then modify the ‘if’ to select the output of one instance or the other. That’s shown above, but I wanted to make clear that’s the reason why.
Now, having done that, if for some reason the variable sel never changes (e.g, with an assign) then synthesis might prune away the unused moduleex instance. But nevertheless both instances of moduleex still need to be declared before the selecting ‘if’, they can’t be declared in it.
The answer that shows modifying the variables to one instance - while correct - misses the point.
if (sel==0)
) and add the always block to make clear. Without any context, this could also be interpreted as agenerate
block \$\endgroup\$if
block - it's a statement. The bit that it is in (e.g.initial
,always
,generate
, etc.) is the block. You can't conditionally instantiate modules within procedural blocks (always
,initial
), but you can ingenerate
blocks. However that only works with parameters, not variables. Remember, you are describing hardware. \$\endgroup\$