r/ProgrammerTIL • u/HoLeeCheet • Nov 02 '17
C# [C#] TIL how this code snippet works.
I thought this was an interesting code snippet / puzzle: What will the array values be after this code executes?
public static void Main(string[] args)
{
int i = 0;
int[] myArray = new int[2];
myArray[i++] = i--;
}A co-worker brought it up today and it baffled me for a while. I'll share the answer if nobody can solve it within a reasonable amount of time.
49
Upvotes
35
u/insulind Nov 02 '17
The value of myArray[0] is 1 because i++ or i-- is post fix increment or decrement meaning the value is captured then changed...I think
61
u/[deleted] Nov 02 '17
The anser is... Fire who ever wrote that code.
10
u/insulind Nov 02 '17
Another way to show this is, is that this doesn't throw an Argument out of range exception as some might think
7
u/houseofmoo Nov 02 '17
Had a question similar to this in undergrad. I believe the array is
{ 1, 0 } at end of block.
In line 3 you evaluate i (0) and use as indexer, increment i (1), then evaluate right side i (1), then decrement i (0).
4
u/thelehmanlip Nov 03 '17
These kinds of surprising puzzles are always the result of really bad code. Kind of interesting, but more annoying than anything.
4
u/[deleted] Nov 03 '17
This does the same thing as
Just unreadably
3
u/Geemge0 Nov 03 '17
It's good to know but you should be shot if you write code like this.
1
u/PancakeInvaders Nov 02 '17
I personaly don't find this kind of things interesting at all or useful to think about, why would any sane dev ever read write an instruction with 2 modifications of the same variable
1
u/adscott1982 Nov 02 '17
i = 0;
new array {0, 0}
array[0+1] = 1 (decremented afterwards) this equates to array[1] = 1, right?
so after the code the values are {0, 1}. But i now equals 0 again.
... I bet I am wrong..
1
u/bautin Nov 07 '17
I'm going to take a stab and say myArray will be [0, undefined] and i will be 0. I'd also accept [1, undefined] with i still being 0.
0
u/nicksvr4 Nov 03 '17
The interesting thing to look for is which side of the assignment operator gets evaluated first. Does it do everything on the right, then assign it to the left? Or does it first look at the left, then do everything on the right and then assign it?
It was my understanding that assignment operations work from right to left, in which case a[-1] = 0, and i = 0.
In this case though, because it's an array, I don't know if it checks the left before looking at the right.