Features of the mql5 language, subtleties and tricks - page 287

 

There is a variable X that can take the values 0, 1 and other values.

When X is 0 or 1, how to quickly and elegantly make it equal to 1 or 0 respectively?

That's the only way I know:

X = X == 0 ? 1 : 0;
 
Andrei Iakovlev #:

There is a variable X that can take the values 0, 1 and other values.

When X is 0 or 1, how to quickly and elegantly make it equal to 1 or 0 respectively?

That's the only way I know:

X = 1 - X;
 
Aleksey Nikolayev #:

didn't realise it myself))

 
Andrei Iakovlev #:

When X is equal to 0 or 1, how to quickly and elegantly make it equal to 1 or 0 respectively?

X = 1 - X;
X = !X;
X ^= 1;
 
fxsaber #:

Thank you)))

 
No difference between any of them, these trivial expressions execute in < 1 nanosecond.

Use the one that makes your code clear.
I would choose the conditional.
 
Andrei Iakovlev #:

Thank you)))

Another option

switch(X)
{
   case 0: 
     X=1;     
     break;
   case 1: 
     X=0;     
     break;
   default:
     break;
}
 
Roman #:

Another option

another

x=(x+1)%2;


 
Alexey Viktorov #:

another


If we proceed from the task " how to make equal faster"...
Then we should reduce possible conventions and operations.
In my opinion switch will be the fastest at the level of assembly registers.

And the remainder from division is an expensive operation.
That's what Renat wrote.

 
Alexey Viktorov #:

another


x = (x + 1) & 1;
x = (int) MathCos(x);
As part of cryptic coding championship.