LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   ++i %= 2; ?? (https://www.linuxquestions.org/questions/programming-9/i-%3D-2%3B-236222/)

Ikebo 09-28-2004 10:36 AM

++i %= 2; ??
 
i = (i+1) % 2;

equivalently:

++i %= 2; // does not work in C
++i %= 2; // works in C++
++i %= 2; // does not work in Java

C I can understand, but why is it that C++ allows a statement like that where even Java says no?

Hko 09-28-2004 03:12 PM

Re: ++i %= 2; ??
 
Quote:

Originally posted by Ikebo
++i %= 2; // does not work in C
++i %= 2; // works in C++
++i %= 2; // does not work in Java

C I can understand, but why is it that C++ allows a statement like that where even Java says no?

First realize that it's a bit of a weird thing to do because "++i" is an expression, and having an expression on the left side of an assignment ( =, %=, += or whatever) looks wrong when you think about it.

But C++ is Object Oriented, and allows you to overload an operator for object classes, like the ++ operator for example. So, in C++, there can be (a reference to) an object on the left side of the assignment, which may have an operator++ method defined. That's why C++ allows you to have a ++ on the left side of an assignment. For consistancy with this, the designers of C++ also implemented this for primary types, like integers, I suppose.

Java doesn't allow this because it does not allow operators to be overloaded.

Ikebo 09-28-2004 04:32 PM

Thank you for the explanation! Very helpful, I wasn't expecting the answer so quickly; I almost expected some spiteful C++/Java debates.

That cleared it right up, thanks!


All times are GMT -5. The time now is 04:44 AM.