Who is who in the use of functions?

Asked

Viewed 312 times

6

I have searched a lot, and has a lot of good content here, which covers this topic, however I still can not understand the functioning.

The characters I’m referring to are:

  • Function
  • Parameters
  • Arguments
  • Values
  • Variables
  • Scope

The answer I have been looking for is an example of a code with 2 or more functions, so that the relationship and the need for this relationship between the characters.

I will try to produce a code that reflects my doubt.

Example

taken from that reply

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

Who are the arguments, what is the relationship with the parameters and the relationship between them and the scope?

  • @rray I have read and reread some 10 times these answers, are complete... But what I do not understand... I think that if the 1st , also addressed the issue, the use and the relationship between parameters and arguments in this context, could be duplicated, join the 2 there duplicates, but still I stay to clarify the relation of parameters and arguments, in the context of functions, block and scope... Really, Ray, I can understand the related answers... but I’m a little short of understanding this whole relationship...

2 answers

9


function funcao(parametro) {
    var variavel = 1;
    return parametro + variavel * 2;
}
var x = 4;
console.log(funcao(x + 3));

I did it in JS just because it’s the easiest one around here. It applies to any language, although the scope usually has some variations in specific cases, not in that.

Function

funcao is the :P function, this is an identifier that references a block of code to be executed. This identifier acts as a constant where its value is the address from which the code for this function is located. Then when the code calls the function there will be an instruction to divert the execution flow of the algorithm to the location where that code is.

This constant may be global in scope (the entire application sees this name), or may be confined to a module, class, etc. So you can only call the function if it is in scope that the code snippet you call has access at that time.

There is a way and declare functions in languages, especially in JS, where that identifier is a variable.

It is common, but not mandatory (because it is not pure mathematics), that the function returns a value. This is usually done with the command return. It is used to terminate the function’s execution flow, usually by returning to the caller.

Wikipedia.

Parameter

This function has declared between parentheses a variable called parametro. Yes, it is a local variable to the function, it only has the life span and time equivalent to the time of execution of the function, exists only within it. But it is a special variable, it is called a parameter because it will receive a value at the time of its call.

Wikipedia.

Argument

When calling the function, in addition to diverting the execution flow to its code, a value is passed to it, this value is an argument.

If there were no scope, that is if all variables were visible in the entire application, which would be terrible to deal with, then it would be almost like doing this:

function funcao() {
    var variavel = 1;
    return parametro + variavel * 2;
}
x = 4;
parametro = x + 3;
console.log(funcao());

The argument can be any expression, it can be a value, it can be a variable or a calculation that generates some value.

Understand the difference between parameter and argument.

We cannot say that the argument has scope, after all it does not have an identifier, its life time is just the time it was created. Do not confuse argument with a variable that is being used as a single element of an expression used as argument. A variable being used as an argument is something only circumstantial.

Note that in the example the argument is the result value of the expression x + 3.

The function funcao() returns a value that is used as argument for the function log() of the object console.

Wikipedia (in the article on parameter has more specific information for computing).

Variable

To variable is just an identifier, so a name for a memory address where there is a value. For the computer that doesn’t matter, it’s just a way for the program to see better what it’s doing. Variable is a form of storage of values with an associated name. We can say that it is only a design standard to facilitate access to values in memory, so used that no one sees it as a design standard.

Function is also a design pattern to segregate a set of codes and create a indirect for its execution. In fact all you do are design patterns embedded in language syntax to make your life easier.

When it is a variable and this saves a reference to an object there is a semantics of its own since any change in the object referencing in parametro will affect what is in the argument variable. But this is not the case for the example.

In the example there is a local variable to função, in addition to the parameter, call variavel, It is not needed there, it was created just to give an example. Then it is used in the expression that will produce the desired result.

There is also another variable called x, also only created to give example, which has scope all the application in this simple example. This is true for Javascript, not ideal that it is so. If you were inside a function, the scope would only be inside the function. This can be seen in the slightly modified example:

function funcao(parametro) {
    var variavel = 1;
    console.log(x); // <========= idealmente não deveria ser acessível aqui
    return parametro + variavel * 2;
}
var x = 4;
console.log(funcao(x + 3));

Wikipedia.

What happens when we call a function?.

Valor

Value is what is stored in the variable, what is inside its object. Variables that are type by value have the value in the variable itself. When it is of a type by reference the value is actually the reference (pointer) and the value that really matters is in an object elsewhere.

see more in Memory allocation in C# - Value types and reference types.

It is common for a value to be defined by a literal, but in many cases it is obtained in other ways through expressions.

Example using a variable by reference where the object is changed:

function funcao(parametro) {
    parametro.a = 3;
    return parametro.a + parametro.b;
}
var x = { a : 1, b : 2 };
console.log(funcao(x));
console.log(x.a);

I put in the Github for future reference.

Javascript passes the reference, but it is immutable, you can only change object, but not the reference itself. Other languages allow the object to be exchanged completely. But this is specific feature.

Note that the scope of variables does not change, but the lifetime of the object changes and is dependent on how the algorithm is executed. The lifespan of variables does not change either.

In the initial example 1, 2, 3, and 4 are literal with values. The return has an expression that will generate another value (it is not stored in variables, it does not need, but it is in memory and then can be assigned to a variable, but it is an independent step. The argument is formed by a value that is also obtained with an expression and is not in variable there, it is only passed to the function. The result of the function is a value that is equivalent to that calculated in the function on the line of the return.

Wikipedia.

Scope

Already Linkei where you can get details (I won’t repeat here, if you have specific questions that are unclear, you can comment there or even put a reward asking for improvements or new answers), but it is only where a certain identifier is visible in the code, that is, where it can be used and will be valid.

Depending on the language the scope can be the function, the class, a specific code block (commonly what is between keys), module (or namespace), even the entire application. What is declared inside cannot be seen outside that code area.

Scope is a concept of coding. It does not matter during execution, it is totally abstracted. Life time is what matters during execution.

The scope has to do with identifiers.

Wikipedia.

Identifier

It is the name given to any object (in a broad sense, no matter what that object is). In general it needs to be unique in a scope (a code region). There are rules of what can be used in that name. It is used to give an identity to the object.

We also call it a symbol.

Wikipedia.

Literal

It is a syntax that explicitly and directly represents a value. It is the value in its most "pure" form. It is more common to be seen in simple objects such as integers and decimals (e.g..: 123, 456.78), but is also used in some more complex, such as string ("texto aqui"), array and object - in the sense of data structure - ({ 1, 2, 3 }, syntax that serves both, depends on the language) and some consider even other objects more nominally (DateTime(2016, 11, 03)), but that is not consensus.

Wikipedia.

Expression

It is the combination of one or more values, constants, variables, operators, and functions that the language interprets according to certain rules and creates a result (a "calculation" is made) that is a new value. The process that calculates this value is called "evaluation".

Wikipedia.

  • The pointer would be the object attribute, or travel ?

  • @Magichat in JS you do not see the pointer ever. For this you would have to do in C, C++, or languages like this, medium level. In JS the pointer is there, but you don’t see or manipulate it. See an example in C where the pointer is manipulated directly: http://ideone.com/DVsU51

  • You see, when I say C is object-oriented, everybody makes fun of me.. kkk Vlw, man ... With all this information I’m sure that if I give a study and do some tests I will understand... Beautiful material...

  • @Magichat if you have specific questions, post.

  • Often specific doubts surround a tide of terms and conditions, but whenever language or inspiration allows me, I try to be specific and objective... Vlw the Force.

  • Seria $this, a type of pointer in JS ?

  • The this in all languages is usually a pointer to the object. One thing I say is that to really learn right is always better to learn from the bottom up, where you understand how the computer works, because there is each thing, and then the abstractions that are being built on top of this, but today almost everyone learn to decorate a house that has no foundation. Looking to know these things, they open doors to know how to use things the right way. I am speaking a little about this in http://answall.com/q/161846/101.

Show 2 more comments

7

Function

A function can be seen as an instruction container, it alone does nothing. It only executes the instructions when it is called.

Parameters and arguments

How @rray commented the difference between parameter and argument is already explained in the other question, but I leave here the essential part:

A function can have parameters. The function caller calls it with certain values (arguments) :

function foo(a/*parametero a*/){/**/}

foo(1) //chama foo com argumento 1, o parametro a toma o valor 1

Variables and values

A variable always has an identifier. Variables store a value. Example:

var a = 1; //variável com identificador a
//a variável a tem valor 1

Scope

A scope is usually defined between the keyhole { and lock lock }

{
   //este é um escopo
}

Based on this definition you come to the conclusion that all functions have a scope as well.

function foo(){
   //este éo escopo da funcao foo
}

Normally variables always belong to a scope and cannot be seen outside it. However scopes can be nested. Child scopes can see parent scope variables. Example:

function foo(){
   var a = 1;
   while(true){
       //este é o escopo do while;
       a++;//o while consegue ver/modificar a
   }
}

The idea of scope is usually a little difficult to understand in depth. For example, the last thing I realized about scopes is that there is nothing to stop you from defining a scope for a certain reason. Example:

function foo(){
    {
        //este código tem uma lógica
        var a = 1;
    }
    {
        //este código tem outra lógica um pouco diferente e eu quero definir um escopo para ele
       var a = 2;
       //nao há qualquer conflito de identificadores porque sao escopos diferentes
    }
}

Based on the comments (and this is important):

Scopes may work differently depending on the language, the example I have just given does not apply to javascript for example...

  • Well didactic, it’s clearing up... let me see the other answer... I’ll understand it today no matter what it costs...

  • var is scope by function, not by block... is wrong what was said there in the last example.

  • @Gabrielkatakura I never spoke of javascript in my reply, or?

  • @Brunocosta ah, sorry, guessed it by custom

Browser other questions tagged

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