# Implicit conversion in glsl shaders

When specifying member values for a structure consisting of float values like vec3 or mat3, is it guaranteed that if an integer value is passed it's going to be promoted to a float? For example if I write

vec3 var = vec3(1, 0, 0)


Same when assigning an integer value to a float variable:

float var = 1


Is the implicit conversion guaranteed here?

Yes, it is guaranteed by the GLSL language specifications (click me). Section "4.1.10. Implicit Conversions" says

In some situations, an expression and its type will be implicitly converted to a different type.

The spec shows all possible implicit conversions inside a table, also int -> float. It further says:

When an implicit conversion is done, it is the same conversion that would be done under explicit conversion, using a constructor.

e.g.

float a = 1;


is equivalent to writing

float a = float(1);


There is one sentence at the end of the section, that you should keep in mind:

The conversions in the table above are done only as indicated by other sections of this specification.

If read it correctly, it says that you can not rely on implicit conversions in any kind of instruction you might come up with. However, regarding vec3 var = vec3(1, 0, 0) section "5.4.2. Vector and Matrix Constructors" says:

If the basic type (bool, int, float, or double) of a parameter to a constructor does not match the basic type of the object being constructed, the scalar construction rules (above) are used to convert the parameters

So it calls the constructor float(int) before consuming each value.

Even though both cases are explicitly backed by the language specifications, my personal advice is to never rely on implicit conversions. They can lead to subtle, hard to track bugs. Not sure how it is in GLSL, since I didn't test it, but in C++ this one:

float a = 1 / 2; # <--- this evaluates to 0.f!


, deeply hidden somewhere in larger calculations, has cost me several hours of debugging more than once. It gets worse if one or both values of the fraction are taken from a variable. However, in C++ I can step through the code with a nice debugger, something that is not so easily done in GLSL. So if the only reason for using implicit conversions is laziness or some sort of taste-related decision, force yourself to be explicit. It will safe you a lot of pain.