-4

I really need someone to explain this part of code float x = Random.Range(0,2) == 0 ? -1 : 1; I understand that it generates a random value of either 1 and -1, and that this float x = Random.Range(0,2) give x a value between 0 and 2, but what does this == 0 ? -1 : 1; do, and how does it function?

4 Answers4

0

This is the conditional operator

The code is equivalent with:

float r =  Random.Range(0,2);
float x;

if (r == 0)
    x = -1;
else
    x = 1;

With the conditional operator x can be initialized while with the equivalent if code I show x must be assigned after initialization. This doesn't matter for float but for other types it may matter.

bolov
  • 72,283
  • 15
  • 145
  • 224
0

As you said Random.Range(0,2) gives a value between 0 and 2. The question mark in this variable assignment is called a ternary operator and works like this: condition ? assign this value if true : assign this value if false.

So in your case if it equals 0, x will be set to -1, if it does not it will equal 1

You can find out more here, at the official Microsoft docs

Cryptizism
  • 89
  • 5
0

A question mark and colon in this circumstance is an inline if statement using the “ternary conditional operator”.

It acts similarly to an if statement but within a larger statement on a single line. For example this:

if( a > b )
    largest = a;
else
    largest = b;

Is equivalent to:

largest = ( a > b ? a : b );

If the conditional statement before the ? is true, the whole clause will become the value immediately after the question mark. If the conditional statement before the ? is false, the whole clause will become the value immediately after the colon (:).

You can use more than one of them in a line, for example:

bool a = false;
int i = 3;
Console.WriteLine(“a is “ + ( a ? “true” : “not true” ) + “ and i is “ + ( i == 3 ? “three” : “not three” ) + “!”);

Note that the “else” is not optional.

So in effect the code you posted is saying “if the random number == 0, x=-1, else x=1”.

Sven Viking
  • 2,660
  • 21
  • 34
0

It is ternary operator, it is similar to if else condition.

For example if you write var x = random == 0 ? -1 : 1; then in terms of if else condition it will be

if(random == 0)
{
  x = -1;
}
else 
{
  x = 1;
}