An interesting coding issue I came across recently was a piece of code that is essentially illustrated by the following snippet:
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int i = 1;
i = i++;
cout << i << endl;
return 0;
}
When compiled with gcc (I tried 4.8.3 on OSX and 4.8.1 on Windows) it generates a warning to hint you at the problem («main.cpp:6:10: warning: multiple unsequenced modifications to ‘i’ [-Wunsequenced]»). The code prints the number 1. The fact that the compiler issues a warning is a very good thing, since this would be very difficult to track.
Interestingly enough Visual C++ 2015 gives no errors or warnings, but instead prints the number 2.
I wonder if the C++ standard has to say something about it…
Out of curiosity I did the same in Java. The similar snippet in Java 8 gives no warning and it prints out the number 1 (as written below).
package foo;
public class Foo {
public static void main(String[] args) {
int i =1;
i = i++;
System.out.println(i);
}
}
Way to go java compiler guys - this is one where a warning would be very helpful.
This is really difficult to find problem - fortunately it is not common :-).