• Post Reply Bookmark Topic Watch Topic
  • New Topic

Literals and promtion  RSS feed

 
Brian K Smith
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote this basic, basic, subroutine to learn a bit about promotions and literals:

OK, I am confused. The error at 1) I get: The result of an integral arithmetic expression has the default width of an int, 4 bytes, the short can not handle it.
Why does 2) Work? Is it because += is an operator, so the short (s) gets promoted? But that doesn't really make sense as there is an assignment to a variable that is still a short?

3) Also isn't the default width of an arithmetic expression like 4 +5 an int, even though the result can easily fit within a short?

4) Is obvious. Needs and F/f.

5) is much the same as 3).
6) I get: Default width of a floating point opeation is a double. See 1). But I am still not clear as to why 1) and 6) fail and 2) does not. I did some very basic poking around on this site, and did not easily find the answer. Any help with explanations or sources would be appreciated.

Thanks
 
Stephan van Hulst
Saloon Keeper
Posts: 7973
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compound assignment operators perform silent narrowing conversions.

Example: a += b is NOT the same thing as a = a + b. It's more like a = (type of a)(a + b). This means that if a is a byte, short or char, or if a is an int and b is a float, long or a double, or if a is a float and b is a double, then the result of the operation is being cast to the smaller data type, and information is lost (narrowing conversion). It happens without a warning (silently).

NEVER use compound assignment operators on bytes, shorts or chars. It may lead to dangerous unexpected behaviour. In general, avoid making calculations using different data types. Results are often confusing.
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Brian K Smith wrote:3) Also isn't the default width of an arithmetic expression like 4 +5 an int, even though the result can easily fit within a short?

The compiler doesn't use 4 + 5. It knows that the result will always be 9, so it actually replaces it with 9. So the statement becomes "s = 9" which is allowed because 9 falls in the range of short.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to the Ranch
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!