What is the difference between scope and lifetime?

What is scope?

What is life time?

Do they get confused?

Visibility has something to do with this too?

Author: Maniero, 2016-06-17

1 answers

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

Scope

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

Other identifiers have scope as well, such as the labels of flow control or functions, or even classes. Nor will I talk about parameters and constants that are very similar to variables.

So we can say that in this context the visibility is a synonym for 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 by leaving some member exposed for external access or not.

Obviously a snippet 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 cannot have two variables with the same name. If you try to do this, in the background it will be the same variable.

There are times when two variables of the same name can 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.

We often call this lexical or static scope. There is controversy 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 each language that adopts it and confusing, so I do not intend to delve into it.

Functions

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 within it. Any attempt to access it outside will cause an error. Others parts of the code are completely unaware of its existence.

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

Blocks

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

It is possible to declare two variables with the same name in a snippet as long as they are in different scopes. Despite using the same name, the variables are completely different. Let's say that a place cannot have two people with the same name, so if it has a "John", any reference to this name will be to this person. When this person leaves and another enters, the same name "John" happens to be used for another person. A typical example is the use for loop control of repetition. 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 the A new scope, the variables do not get confused.

Is "good practice": D make the variable as scoped as possible.

Expression

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

Module or file

O scope can be a class, module, or something like that. Variables that are outside of functions, but are part of some data structure.

A specific type can be a file. Some languages do not have great granularity to specify a wide scope, and the file is for this.

Global

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

Linkage

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

Life Time

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

If it is a variable the lifetime 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 just 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, so eventually have a longer life time 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 mechanism with similar effect.

There is the lifetime of the value of the variable, which can be just a reference and has the lifetime of the object it refers to.

In general when a variable goes out of scope, if its value (same referenced) is not bound to something, its lifetime ends, or at least becomes inaccessible. But there are cases when the object passes to another owner, maintaining its lifetime.

Memory allocation to the variable/object can have multiple 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 often keep allocated data even after its lifetime end. allocation pools can be used.

Some data types are always static and have a lifetime for the entire duration of the application. This is the case with 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 on GitHub for future reference .

The exact functioning depends on the language.

 35
Author: Maniero, 2020-06-11 14:45:34