Sequence of execution of tasks

Asked

Viewed 41 times

0

I have a question about the execution sequence. For example, in the code below, because it prints y=2.0 and not y=4.0 and because it prints w=0.5 and not w=2.2. y=2.0 understands that it looks for the value that is closest. So far so good. But why w=0.5 and not 2.2 what is the value of the global variable? Is there some sort of execution priority?

float w = 2.2;
float y = 3.0;
void setup(){
  y = 2.0;
 float x = fn(w + y, y);

 println(x + "," + y + "," + w);
}
float fn(float x, float y){
 w = 0.5;
 y = 4.0;
 return w + x + y;
}

1 answer

0


We start in function setup defining the value of y and calling the function fn:

float w = 2.2;
float y = 3.0;

void setup(){
  y = 2.0; //alterar o y global
  float x = fn(w + y, y);
//resulta em fn(2.2 + 2.0, 2.0); => fn(4.2, 2.0);

That calls the function fn with the values indicated above. This will now set values and return a result:

float fn(float x, float y){
  //--------------------^ Parâmetro com nome igual a uma variável global que acaba 
  //                      por esconder essa variável global

  w = 0.5; //alterar o w global
  y = 4.0; //alterar o parametro y da função para 4.0, deixando o y global em 2.0
  return w + x + y; 
//return 0.5 + 4.2 + 4.0 = 8.7
}

Note that the instruction that changes the y only affects the function parameter and not the y global because the name is equal.

After the return we make the print:

println(x + "," + y + "," + w);
//      8,7  ,    2.0  ,   0.5

The w got 0.5 because the change within fn affected the w global, since there was no function parameter with the same name.


Note: Literal floats must carry the f at its initialization, leaving something like:

float w = 2.2f;

Otherwise they will be interpreted as doubles.

  • If I comment y=2.0 right away from the setup() function, why not y=4.0 and take the overall value?

  • 1

    The function fn has a parameter called y. So anything that relates to y within that function refers to the parameter and not the global one. The problem is that the name is equal

  • I had one more question on this subject. In this example the change method is useless? :void setup() {
 int[] x = {1,5,7,2};
 println(x);
 change(x);
 println(x);
}
void change(int[] a){
 a = new int[]{1,2,3};
}

  • @Jsi83 Even so, assign a new array to the parameter a in the method change does not alter the original that was in the method setup

  • But what’s the difference here? Because here I change the element in index 2 and in the example above I do not change the array? void setup() {
 int[] x = {1,5,7,2};
 println(x);
 change(x);
 println(x);
}
void change(int[] a){
 a[2] = 9;
}

  • @find83 The difference is in changing an element at a position or assigning a new array. array[posicao] = outrovalor; versus array = new int[quantidade]

Show 1 more comment

Browser other questions tagged

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