Println order help?

Can someone explain me the order of printlines here?

int a = 4;
int b = 7;
void setup() {
 println("Setup: " + knutsel(a, b));
}
int knutsel(int b, int a) {
 println("Knutsel: " + a);
 println("Knutsel: " + b);
 return kwispel(a, 2*b) + b;
}
int kwispel(int a, int b) {
 println("Kwispel: " + a);
 println("Kwispel: " + b);
 return a - b;
}

the result =
Knutsel: 7
Knutsel: 4
Kwispel: 7
Kwispel: 8
Setup: 3

Hi!

Function calls are not evaluated until all its arguments are evaluated.

So you should not read the code as if it was English, but from the inside out. It does not print "Setup: " and then go find out how much knutsel() is worth. Instead, it first evaluates knutsel() and when that value is known, then it can run the println() inside setup().

The same sequence happens with simple math and parenthesis. You start from the inside. For instance:

4*((3*(1+2))-2) = 
4*((3*  3  )-2) = 
4*(   9     -2) = 
4*       7      =
28

So with the println, if you call

println("the result is " + (3*3));

it will not first print "the result is " and then figure out 3*3. What it will do is first figure out 3*3 which is 9 and then print the whole string at once.

Does that solve the mystery?

3 Likes

Nope it doesn’t solve the mystery :frowning:

So what order do you expect instead?

Maybe the confusion is that in knutsel the a and b arguments are swapped? So what was a is now called b, and the other way around?