Reputation: 133
I test this code
int value = (char)+(int)-(float)+(double)-1;
and I get this result (1) that means value is 1
! How is this calculated?
EDIT:
I had an interview yesterday in a company and this was their question, and I did not know how this number was obtained 1
. So I am trying to understand how this result comes about.
Upvotes: 4
Views: 199
Reputation: 16693
It's a matter of simple arithmetics:
(double)-1
is calculated to -1
(float)+(double)-1
is calculated to -1
(int)-(float)+(double)-1
is calculated to +1
(char)+(int)-(float)+(double)-1
is calculated to +1
Upvotes: 0
Reputation: 3052
The calls:
int value = (char)+(int)-(float)+(double)-1;
int value = (int)-(float)-1;
int value = 1;
Have the same Intermediate Language that push the number 1 into 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 reduce your operation to a simple assigment.
Upvotes: 5
Reputation: 119146
This is really just a lot of casting. The +
and -
signs are only being used to negate the number. So take the first bit of the expression, that casts -1
to a double
:
(double)-1
Then take the result of that and cast it to float
:
(float)+(-1)
And so on until you end with a char
that is implicitly cast to an int
.
Upvotes: 8