What’s the difference between scope and lifespan?

Asked

Viewed 2,413 times

43

What is scope?

What is life time?

They get confused?

Visibility has something to do with this too?

1 answer

36


They may get confused in some situations, but they are completely different concepts. There are cases where life time seems to be equal to the scope, so it looks like it’s the same thing.

Scope

This is a compilation time concept. Scope (at least static) exists in the source code text, you discover it by reading the code. It is an indicator of the lifetime of a binding of a name with a value. In general this refers to variables. It refers to which parts of the code the variable is visible/accessible.

Other identifiers also have scope, such as Labels control of flow or functions, or even classes. I won’t even talk about parameters and constants that are very similar to variables.

So we can say that in this context the visibility is synonymous with scope. The term visibility may have another meaning in other contexts. I will not go into detail because it is not the focus, but there are cases that visibility can be controlled leaving some member exposed for external access or not.

Obviously a chunk of code cannot access a variable that is out of scope. The fact that a variable is declared does not mean that it is always available. Depending on where it is declared it may be visible to the code or not (note that the visibility of what is written is something else).

Within the same scope you cannot have two variables with the same name. If you try to do this, at the bottom it will be the same variable.

There are times when two variables of the same name may be "in scope". Languages have rules to determine which of the two variables will be used and usually provide some mechanism to reference the other if necessary. There the programmer is obliged to disambiguate what he wants.

Often we call this lexical or static scope. There are controversies whether it can be used correctly in this context.

In some cases the scope can be dynamic and defined at runtime. This is rare, specific to every language that adopts it and confusing, so I don’t intend to delve into.

Function

The most common scope is that of the function. Most languages are quite strict about this. A variable declared within a function (or method, of course) is considered local and can only be accessed inside. Any attempt to access it outside will cause an error. Other parts of the code are completely unaware of its existence.

Remembering that closures are functions and can capture variables created in another, more external scope, increasing the lifespan of your value.

Blocks

Another common scope is the block. This can be a loop, conditional, exception or other type of block. In case of blocks that are related (if/else) some languages treat it as just a single block.

It is possible to declare two variables with the same name in a section as long as they are in different scopes. Despite using the same name, the variables are completely different. Let’s say a place can’t have two people with the same name, so if you have a "John," any reference to that name will be to this person. When this person leaves and another person enters, the same name "John" is used for another person. A typical example is the use for loop control. Some programmers who do not understand this concept tend to create a variable for each loop. It is not necessary, one loop is a scope, and the other is a new scope, the variables are not confused.

It is "good practice" :D to make the variable have the smallest possible scope.

Expression

It is common to be able to define a more specific block still, in general a specific expression, a loose block that is not a flow control.

Module or file

The scope can be a class, module or something like that. Variables that are out of function but are part of some data structure.

A specific type can be a file. Some languages do not have large granularity to specify a broad scope and the file serves for this.

Global

It is valid anywhere. It is often confusing and should be used sparingly, especially in large applications.

Linkage

There are languages that allow the same variable or identifier to be declared(o) in two different locations referring to the same value or purpose. It is a way of scoping something that is in another scope without creating something new.

Lifespan

This is a runtime concept. It may be related to variables, but also to objects in general. Refers to data storage.

If it is a variable life time refers to the time it is available for access, or at least when it has a value with meaning to the code. In some situations it is equal to the scope.

It is important to differentiate variable, which is only the name given to a value, as already defined, and the value to which it refers. Life time has more to do with value. A value can survive even if the variable dies, a variable can change its value, therefore eventually having a lifetime longer than the value.

Survives when:

  • the value is returned at the end of a function
  • the value is assigned to another variable in larger scope (may be another data structure)
  • the value is assigned within a closure or a mechanism having similar effect.

There is the life time of the variable value, which can be only a reference and has the life time of the object that it refers to.

In general when a variable goes out of scope, if its value (even referenced) is not linked to something, its life time ends, or at least becomes inaccessible. But there are cases where the object passes to another owner, keeping its life span.

The memory allocation for the variable/object can have several strategies and only coincide if it is of interest to the application/language. As well as the location where the allocation will be made. Languages with garbage collectors tend to keep data allocated even after its lifespan runs out. Pools allocation can be used.

Some types of data are always static and have lifetime for the entire duration of the application. This is the case for functions (the code itself) and static variables.

Example

class Teste {
    int x = 5; //escopo da classe, tempo de vida de acordo com a instância
    StringBuilder txt; //o mesmo
    int Metodo(int y) { //parâmetro existe dentro da função escopo/lifetime 
        var x = 2; //note que há ambiguidade com a variável da classe
        var t = new StringBuilder(10); //variável e objeto locais vivem até a função
        for (var z = 0; z < 10; z++) { //só existe dentro deste bloco
            WriteLine(this.x * x + y * z); //desambigua e usa todas variáveis
        } //z morre aqui
        //uma tentativa de acessar z aqui produziria erro
        for (var z = 0; z < 10; z++) { //este z é diferente do outro
            t.Append(z.ToString()); //declarada fora, continuará existindo no fim do bloco
        } //z morre aqui
        txt = t; //a variável vai morrer o seu objeto sobreviverá em txt
        return x; //o valor será copiado para algum lugar, será um novo objeto igual
    } //aqui morrem x (local), y, t (não seu objeto, qua ainda tem referência)
}
static class Program {
    static int x = 10; //escopo desta classe tempo de vida da aplicação
    static void Main() { //só existe dentro desta classe
        StringBuilder t; //vive por toda função
        { //inicia um novo escopo
            var y = new Teste(); //variável e objeto têm escopo e tempo de vida deste bloco
            x = y.Metodo(3); //este x nada tem a ver com o x da outra classe, nem poderia
            t = y.txt; //o texto ainda viverá
        } //y morre aqui, seu objeto precisa viver mais porque tem uma referência para ele
        WriteLine(t); //o texto 0123456789 será impresso, ainda vive
        //não é possível acessar o conteúdo de y mais, mesmo o objeto estando vivo
        //o escopo acabou,só a referência previamente existente ainda pode acessar o objeto
    } //aqui morre t e finalmente o objeto criado por new Teste()
} //note que x não segura uma referência para o objeto, seu resultado é uma cópia
//código para demonstração simples, não faça isto em casa

I put in the Github for future reference.

The exact functioning depends on the language.

  • 1

    every post of yours is a haha class :P

  • done, keep up the good work. ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.