René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

Comments on the modulus and increment operater in C++ and Java

Today, Frederic Barachant has written an eMail: C/C++ and java increment, plus other things which I found interesting. I have allowed myself to make it available for the public here.
hello
I've been on your pages due to googling on JGenerator and then discovered laszlo while reading further. I didn't contact you primarly for that, but when i did read the "Precedence of the modulus (reminder) and the ++ (incrementing) operator in Java and C++" page, i remembered one funny thing i did experiment some time ago with that...
what would you expect in C from something idiot like
int a = 10; 
a = (a++ ) + (a++); 
Well, you might say 23, which would be the intuivite result you'll first think about.. something like, "heh, 23, or course, dood."
.. in fact, it can be 23 or 22 or 21, depending on how the compiler did the work and it will be 21 in Java, wherever you try it.
In fact, C specs don't tell when increments have to be done, leaving the choice to compiler programmers. Thus, some compilers have different behavior with it: incrementing after the whole expression, or one time per variable, but before using the variable into closest operator... It gets worse if you mix pre and post increment. things like a= ++a+a++; can be pretty funny to watch.
I used to try with VC and GCC (and watcom iirc) and got different results, that was years ago, and i don't know if the behavior changed. (which would be bad, but...)
Good thing with Java is that the spec says that pre have to be done immediatly and post are done once value is used in closest operator so at least you know what to expect. Anyway, here is the reason why it does not give what you expected. As post increment in Java works after the value has been used by the operator of the value, which really means that "A has to be incremented after it's been read here", once decomposed, your operation is:
push  a%7 
a+=1; 
a pull;  
where increment is totally nullified, which is totally consistent with specs.
In that precise operation, C might or not make a difference between pre or post increment (ever wondered while typing "why the hell doesn't it make any difference if i use pre or post increment here?"), while Java does. if you were using pre increment, your snippet would have work because it would have given
a+=1; 
a = a%7; 
If you try your snippet on an other C compiler, you might obtain values between 1 and 7(a=a%7;a++;), values always 0(same behavior as java), ....which would be definitly worse.
I agree in advance with you that the example should really not be a real life one, but it does not mean that it has no implications anyway. Maybe we've not been tricky enough :)