Function execution sequence

0

I have a question about the execution sequence of functions. 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. The y = 2.0 understand that it looks for the value that are closer. So far so good. But why w = 0.5 and not 2.2 what is the value of the global variable? Is there any 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;
}
    
asked by anonymous 20.11.2017 / 02:21

1 answer

0

We start in the setup function by setting 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 statement that changes y only affects the function parameter and not y global because the name is equal.

After the return we do the print :

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

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

Note: The literal floats should take f at startup, something like:

float w = 2.2f;

Otherwise they will be interpreted as doubles.

    
20.11.2017 / 02:42