Can't use 'const int' in a switch statement in Godot shading language

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By kitfox

Was writing a shader and discovered that I do not seem to be able to declare constant ints and then use them in a switch statement:

const int flagA = 1;
const int flagB = 2;

void myFn(int val)
	switch (val)
		case flagA:

Is there any way to declare constants in a shader? I’d rather used named contants than write the integer values everywhere.

:bust_in_silhouette: Reply From: klaas

HI …


Use the const keyword before the variable declaration to make that variable immutable, which means that it cannot be modified. All basic types, except samplers can be declared as constants. Accessing and using a constant value is slightly faster than using a uniform. Constants must be initialized at their declaration.

const vec2 a = vec2(0.0, 1.0);
vec2 b;

a = b; // invalid
b = a; // valid

Constants cannot be modified and additionally cannot have hints, but multiple of them (if they have the same type) can be declared in a single expression e.g

so … yes you can … the error must be somewhere else

ah … i see what you mean.

No, idont think so. Variables initialized with const are still variables. But switch case only accept true constants. This would require a preprocessor.

You have to switch to if else statments(wich are slower) or use the bare integers.

klaas | 2020-08-23 15:14