# Is there different between 'if' and 'ternary operator' in GLSL?

void mainImage( out vec4 fragColor, in vec2 fragCoord ) {

vec2 coord = fragCoord.xy/iResolution.xy;

vec3 background = vec3(1.);

vec3 axesColor = vec3(1.,0.,0.);
vec3 gridColor = vec3(0.85);

vec3 color = background;

const float tickWidth = 0.1;
for(float i = 0.0 ; i < 1.0 ; i += tickWidth)
{
if(abs(coord.x - i) < 0.002) color = gridColor;
if(abs(coord.y - i) < 0.002) color = gridColor;
}

if(abs(coord.x) < 0.005) color = axesColor;
**if(abs(coord.y) < 0.005) color = axesColor;**
**//color = abs(coord.y) < 0.005 ? axesColor : background;**

fragColor = vec4(color,1.0);  }


my question is on last 3 lines.

First, I used ternary operator for branch, but it made weird result that only drawing "x axes".

However, when I changed the operator to if, it works well. The code drew x, y axes and all grids as I wanted.

So I wonder is there different between if and ternary operation in GLSL? If that, how can I choose correctly?

The difference is obvious. The ternary operator will return one of the two alternative values it is given; that's what it is for. An if condition that doesn't have an else block won't do anything if the condition is false.
The ternary operator version will set color to axesColor or background. But by that point in your code, you've gone past 3 other conditions that may have changed the value of color from its initial value of background. But the ternary operator doesn't care. It will overwrite whatever is in color with either axesColor or background.
What you probably wanted was color = abs(coord.y) < 0.005 ? axesColor : color;, so that the value will be preserved if the condition is false.
• @FelipeGutierrez: That has nothing to do with the issue here. That's a matter of optimization. The OP's issue is that the if version specifically does something different from the ?: version. Because they're supposed to do different things; the statements aren't equivalent. – Nicol Bolas Nov 9 '20 at 3:37