Every function that's called creates an activation record inside the call stack with all the information withing it (including the address of the variables that are accessible for that scope), and allocating/reserving the slots in memory that it needs. Whenever the function finishes whatever it was doing, the activation record is popped from the stack and the memory freed by removing all the local variables that are being created.
The thing with global variables is that they're declared outside any particular scope or lifetime, so they'll last as long as the program or instance of whatever file its in lasts and will be accesible to anything in the call stack from there on, so that way you'll be able to access val from whatever function you declare below func.