GLSL for loop condition expression: how can it be a declaration?

The spec says a for loop is:

for (init-expression; condition-expression; loop-expression)

And then they say:

Expressions for condition-expression must evaluate to a Boolean.
Both the condition-expression and the init-expression can declare and initialize a variable

And the grammar has:

condition :
    fully_specified_type IDENTIFIER EQUAL initializer

I’m confused about to use this condition expression variable initialization case. I’ve tried this in WebGL 1 GLSL:

for(int i = 0; bool x = i < 10; i++) {}

And the angle compiler errors and tells me me:

Expected loop index

Can someone provide valid syntax for declaring a variable in the condition expression? Also, in GLSL, do declarations evaluate as expressions? Aka does bool x = false; as a statement also evaluate to false if used in the context of an expression?

I’m working in WebGL, GLSL ES 1.0, and I wonder if this is GLSL ES 3.0 only, or if I’m missing something.

The spec (at least GLSL 4.6) talks about this, but within a context where it’s talking about all of these:

for (init-expression; condition-expression; loop-expression)
while (condition-expression)
while (condition-expression)

It is possible that it is only talking about the “condition-expression” term of while (and not the do-while version either). Then again, “condition-expression” is not a valid term in the grammar.

Alternatively, in C and C++, definitions are legal in the condition clause of a for loop, but only really because for is explicitly defined in terms of while.

Can someone provide valid syntax for declaring a variable in the condition expression?

I wouldn’t take Angle’s word for it with regard to what is and is not valid GLSL grammar. Assuming “condition-expression” is a condition term, then the code you wrote is valid.

I was able to verify that this compiles in WebGL2 / GLSL ES 3.0:

for(int i = 0; bool x = false; i++) {}

So looks like it’s just not available syntax in GLSL ES 1.0. I’m still confused on if that whole declaration returns the value false, or if it’s some magic specific handling of the condition-expression by compilers.

According to appendix A:

Ultimately, there’s not much point in using a declaration in a condition expression, as the body will never be executed with the variable having a value other than true. Section 10 (Issues) has this to say:

With implicit type conversion, you could have

for (...; int x=f(); ...)

with the loop body using the value of x (which could be any non-zero value).

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.