LinuxQuestions.org
Latest LQ Deal: Latest LQ Deals
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 09-28-2004, 10:36 AM   #1
Ikebo
Member
 
Registered: Jun 2004
Location: Michigan, USA
Distribution: Ubuntu
Posts: 77

Rep: Reputation: 15
++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?
 
Old 09-28-2004, 03:12 PM   #2
Hko
Senior Member
 
Registered: Aug 2002
Location: Groningen, The Netherlands
Distribution: Debian
Posts: 2,536

Rep: Reputation: 111Reputation: 111
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.

Last edited by Hko; 09-28-2004 at 03:14 PM.
 
Old 09-28-2004, 04:32 PM   #3
Ikebo
Member
 
Registered: Jun 2004
Location: Michigan, USA
Distribution: Ubuntu
Posts: 77

Original Poster
Rep: Reputation: 15
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!
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 06:20 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration