|
|
|
||
|
A question was recently posted on the CJUG forum with regards to the following code:
int i;
i = 1;
i = i++;
System.out.println("i: " + i);
The poster wanted to know why in Java the result was If you're like me, the first thing that popped in your head was: This person does not have a clear understanding of the postfix increment operator does. Let's tell him to go suck an egg and get a clue. But then I remembered back to the days when I didn't know what I was doing either and all of the kind and gentle people on usenet that steered me onto the path of knowledge. In case you're having trouble getting over that hurdle, you can look at the problem as follows:
int[] a = { 0, 1, 2 };
int i;
i = 1;
a[i] = i++;
System.out.println("a[0]=" + a[0] + ", a[1]=" + a[1] + ", a[2]=" + a[2]);
which is slightly more palatable and results in the following: a[0]=0, a[1]=1, a[2]=2 I'll spare the long winded answer to the reason why Java returns what it does and refer you to a Java forum posting. (Though if you want me to ramble on about it, just ask!) That takes care of the Java part, but what about C / C++? Well, if you didn't get all soft and squishy developing in Java all these years, you'll remember that the order of evaluation of operands of individual operators and the order in which side effects take place is unspecified in C / C++. You'll also start remembering about sequence points and all of that but before you begin to spasm uncontrollably, you'll remember that you've left all that behind you now. At the end of the day, the fact that the particular C / C++ compiler, runtime, etc resulted in
...in C that statment might assign 0, 1, 42, -1 or any other value to There is also Steve Summit's famous response which provides links to the C FAQ for more information. |
| Comments | ||||||||||||||
|
| Post a comment |
|
|
Unless otherwise expressly stated, all original material of whatever nature created by Rob Grzywinski and included in this weblog and any related pages, including the weblog's archives, is licensed under a Creative Commons License. |