• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

+= and ++

 
Satish Sangapu
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How come the following work?
byte a=2,b;
b=a+1; // doesn't work - needs a cast
b=a++; // it works, why? - shouldn't it need a cast?
long L=1;
int i=0;
i=i+L; // not okay - needs a cast
i+=L; // okay, why? - shouldn't it need a cast also?

 
jayanthi
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when +=,++ is used cast is automatic
 
Barbara Dyer-Bennet
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The statement b = a++ works not because there is an automatic cast, but because a is incremented as a byte and assigned to b, which is also a byte.
In the statement i = i + L the cast is automatic, and it is to a long type. A long won't fit into the int on the left side of the assignment operator, so you have to do an explicit cast to force the issue.
The statement i += L works because of the compound operator; i becomes a long because the largest data type in the expression is a long. I hope this hslps.
[This message has been edited by Barbara Dyer-Bennet (edited September 15, 2000).]
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried the same with double i.e saying i+=d(where double d=1.0)and when i displayed it on console I'm getting int value and not as double as pointed out...(that the compound statement will be casted to largest data type in the expression) .
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
i tried with bytes byte b1=1,int i=1;and when i perform b1+=1;
it is giving explicit casting is required...i could not get to
final conclusion on this..is there any version problem..
 
softie
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Satish,
I agree with barbara. it is that when the += operator is used its equivalent to the operator and cast before the right side. whereas its not the case with + operator.

Cheers
Satish
 
jayanthi
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
with +=, ++ cast is automatic
i think so...
jayanthi
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OOPs!! I posted it wrongly, b1+=1 is working fine.
Sorry for the mistake..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic