why here cout<<y*x; we did not use parenthesis but we got no error |
As has already been said, it's down to order of precendence.
Have you looked at the tutorial keskiverto pointed you at?
Operators
http://www.cplusplus.com/doc/tutorial/operators/
The table at the end (in the "Precedence of operators" sections) shows that operator* has precedence level 5, whereas operator<< has level 7 and operator+= has 15.
And when evaluating an expression, the higher level (1 is highest) operators are evaluated before the lower level ones. So * is evaluated before << but << is evaluated before +=.
When operator* is evaluated first, all is OK as operator* returns a value of the same type as its operands. e.g. <int> * <int> -> <int> in this case, and operator<< knows how to write out the resultant int.
When operator<< is evaluated first, before +=, it all goes wrong. The overload for writing ints (omitting the std namespace qualifier) is
ostream& operator<<(ostream&, int)
So its the temporary ostream returned by the evalution of
cout << y
that you're trying to increment with
+=x
, But ostream does not support this operator so it doesn't work.
Andy
PS It is a bit confusing that the bitwise shift operator is overloaded for stream insertions (that is, output), but it has the same precedence when used for stream operations as bitwise ones.
Why are bitwise shifts (<< and >>) used for cout and cin?
http://stackoverflow.com/questions/4854248/why-are-bitwise-shifts-and-used-for-cout-and-cin