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?
– find83
The function
fn
has a parameter calledy
. So anything that relates toy
within that function refers to the parameter and not the global one. The problem is that the name is equal– Isac
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};
}
– find83
@Jsi83 Even so, assign a new array to the parameter
a
in the methodchange
does not alter the original that was in the methodsetup
– Isac
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
@find83 The difference is in changing an element at a position or assigning a new array.
array[posicao] = outrovalor;
versusarray = new int[quantidade]
– Isac