Overview

Scope in verilog or systemverilog ideally refers to the space inside the code where the variable exists and is visible. This also means that once the simulator executes the last piece of code in a defined scope, everything which was created inside the scope will cease to exist and the garbage collector frees up the system memory by deleting the variables and other instances.

The simplest example for a scope can be explained with begin-end . Any memory created for anything inside the being-end, will only exist as long as the simulator is still executing code inside the begin-end. Once it reaches the end keyword, the garbage collector is called. Some of the keywords which act as scope boundaries are given below:

begin-end
fork-join
task-endtask
function-endfunction

If noticed properly, you will see that only blocks which can be used dynamically are mentioned. This is because other blocks like module-endmodule are static in nature, and although also constitute as scopes, the garbage collector does not work in the same way for it as for the others. In case of module-endmodule, memory is already created in elaboration stage of simuation, and will exist throughout the simulation.

Theory Questions
    function test;
        integer a;
    
        begin
            begin
                integer b;
                
                b = $random;
                $display( "b : %0d", b );
            end
                
            $display( "b : %0d", b );
        end
    endfunction
    
    Locked Solution
    Locked Solution
Coding Questions
    module top;
    
        initial
        begin
            fork
            begin
                integer a;
                a = $urandom;
            end
            begin
                #100;
            end
            join
        end
    
        initial
        begin
            // Print the a's value here
        end
    endmodule
    
    Locked Solution