Interesting(?) type coercion


#1

Hi!

Starting with

int framePer = floor(1000./frameRate),  bgTO = 1000;    //  <- this is not interesting

This is ok:

int dClr = floor(255*framePer/bgTO);                    //  <- expected

This fails with a ‘can’t float to int’

int dCl1 = 255*framePer/bgTO;                           //  <- expected

as does this:

int dCl2;  dClr2 = 255*framePer/bgTO;                   //  <- expected

as does this:

int dCl3 = 0;  dClr3 = 255*framePer/bgTO;               //  <- expected

this fails with a ‘may not be initailized’:

int dCl4;  dClr4 += 255*framePer/bgTO;                  //  <- expected

but this compiles just fine:

int dClr5 = 0;  dClr5 += 255*framePer/bgTO;             //  <- this is the interesting one

This is an example of a ???

Thanks
Doug


#2
int framePer = floor(1000/frameRate);
int bgTO = 1000;
int dClr5 = 0;
dClr5 += 255*framePer/bgTO; // <- this is the interesting one
println(dClr5);

25

Integer division is not type coercion. When you divide an integer by an integer, you get an integer.

https://processing.org/reference/divide.html

If this seems strange conceptually, think about it in terms of non-divisible goods – so not apples, but pants. We have 12 pairs of pants, and 5 people. How many pairs of pants can each person have? 2. 12/5 = 2.


#3

Java’s compound assignment operators, like +=, /=, ^=, etc., got auto coercion.
While the single assignment operator = doesn’t auto coerce at all.


#4

Thanks @GoToLoop!

Know why that is? I would think strong typing would be more consistent.

Doug


#5

But just to make sure it is clear, note that your example above is NOT type coercion. int * int returns int. int * int / int returns int. So int += int * int / int is the same as int = int * int / int – both run the same way, because both assign an int to an int.

int framePer = floor(1000./frameRate),  bgTO = 1000;
int dClr5 = 0;
dClr5 += 255*framePer/bgTO;
println(dClr5);  // 25
int dClr6 = 255*framePer/bgTO;
println(dClr6);  // 25

It is true that += would coorece the float to an int, but in your example there is no float to convert. This would be an actual example of that happening in practice:

int x = 0;
x += 1.5;
println(x);  // 1
x = 1.5;     // error!