Challenge: What does this code do?
Without compiling this, can you answer me whatever this piece of code will compile? And if so, what does it do?
var dummyVariable1 = 1; var dummyVariable2 = 3; var a = dummyVariable1
+-+-+-+-+ + + + + + +-+-+-+-+-+
dummyVariable2;
Oh, and I want to hear reasons, too.
Comments
First I thought I will compile but after I look at the MSDN it said "Variables declared by using var cannot be used in the initialization expression" so the last line probably throw an error.
I had to cheat and fire up the compiler :-\ (feel free to delete this if I'm spoiling the surprise). I guessed no as I didn't realise that + could be a unary operator.
You end up with dummyVariable1 + (expr), where expression consists of alternating the sign of dummyVariable2 using the unary forms of + and -. It ends up as dummyVariable1 + (-dummyVariable2), or -2.
I don't want to think about how you came up with this :-S :-)
One for the old pen and paper.. It should boil down to 1 + -3 as there are nine negative operators in the expression, the positive operators can be reduced which should make it equivalent to dummyVariable1 + -(-(-(-( -(-(-(-(-(dummyVariable2))))) )))) if I got all the brackets in there correctly or more simply 1 + ---------3 == 1 + -3 = -2. So yes it should have no problem compiling :)
I don't know, and don't care. There should be laws against code like this.
LOL! Why is that Thomas?
@Dave - "Without compiling this..."
So amazing that you could run this and come up with the answer.
@Sammy - Because it's not readable... at all :) But that's not the point to this post anyway.
I suspect it does compile, but I don't care. This code causes any one reading such code to become homicidal and begin searching for the masochist who wrote such code. The reason? My God, if you have to ask .... :-P
@JC,
I wasn't trying to amaze. I can't help my lack of innate intelligence, hence I resorted to cheating :)
The reason for my comment was that my "without compiling this..." guess was dead wrong. I thought I'd cover the "giving reasons" part of the challenge instead :) .
I could have just omitted to mention I compiled it, but wanted to illustrate one key way someone could get the problem wrong. Sorry if I spoiled it for you :-\
@JC, you're quite right though -- it was a silly thing to do. Note to self: think before pressing submit. Consider my intraweb pass revoked :)
I've had questions like this on interviews and always feel like saying "if anybody in my team wrote code like this, I'd tell them not to", there's no point ...
@Dave - no prob, I just felt like being rude that day :)