I don't understand how this phrase is computed in C #
I am testing this code
int value = (char)+(int)-(float)+(double)-1;
and I get this result (1) which means that the value 1
! How is this calculated?
EDIT:
Yesterday I had an interview with a company and that was their question and I didn’t know how this number was obtained 1
. So I am trying to understand how this result happens.
source to share
It's really just a casting. The +
and signs -
are used only to negate a number. So, take the first bit of the expression, which differs -1
from double
:
(double)-1
Then take the result of this and draw it onto float
:
(float)+(-1)
And so on, until you are done with char
, which will implicitly be passed to int
.
source to share
Challenges:
-
int value = (char)+(int)-(float)+(double)-1;
-
int value = (int)-(float)-1;
-
int value = 1;
Have the same intermediate language pushing number 1 onto the evaluation stack:
IL_0000: nop
IL_0001: ldc.i4.1 // <-- push to stack
IL_0002: stloc.0 // value
IL_0003: ldloc.0 // value
IL_0004: call LINQPad.Extensions.Dump<Int32>
IL_0009: pop
IL_000A: ret
Optimization reduces your operation to a simple set.
source to share