Hi,
What is the difference in a Unity shader between if (xx = …) , and if (xx ==…)
Both of them work, with different results… What is the difference between them?
Thanks!
Hi,
What is the difference in a Unity shader between if (xx = …) , and if (xx ==…)
Both of them work, with different results… What is the difference between them?
Thanks!
tl;dr: Shader allows you to assign and compare an integer for zero at the same time.
Long explanation: we have to break it down a little bit.
First, shader language is closer to C than to C#. In C you can do some weird acrobatics when it comes to comparison and assignment.
Let’s start with C# first. If I wanted to assign a value to a variable, then compare for equality, I can do this:
int x = 0;
if (x == 0) {} // true
if (x == 1) {} // false
Now, C# is strict in the way if
works. It can only evaluate bool
types. So if you tried to do this:
if( x=0 ) {} //error
It won’t compile. However, C (and Shader language) is a bit more flexible. “If” statements do not compare for bool, but whether a value is zero or not, so this:
if (true) {}
is the same as this:
if (1234){}
and
if (false) {}
is the same as this:
if (0) {}
with that in mind, you can assign a value and compare it at the same time. So you can do weird stuff like this:
if (x = 0) {} // false
if (x = 1) {} // true
Which is kind of pointless, but you often see it used in places like this (in pseudo-C)
if ( bytesRead = read(buffer, 1, 1024))
{
printf("We read %d bytes ", bytesRead);
}
So you’re calling a function, getting the result value, assigning it to a variable and checking if it’s zero all in one line
PS: You shouldn’t be using “if” in shaders anyway. They tend to perform poorly. :3