Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are operands inside an expression promoted to larger types according to the following rules?

If numeric expression contains operands (constants and variables) of different numeric types, are operands promoted to larger types according to the following rules:

  1. if operands are of types byte, sbyte, char, short, ushort, they get converted to int type
  2. If one of the operands is int, then all operands are converted to int
  3. if expression also contains operands of types uint and int, then all operands are converted to long
  4. If one of operands is long, then all operands are converted to long
  5. if expression contains operands of type ulong and long, then operands are converted to float
  6. If one of the operands is float, then all operands are converted to float
  7. if one of operands is double, then all operands are converted to double

Assuming numeric expressions contains operands of different types, will all operands first get converted to a single numeric type, and only then will the runtime try to compute the result? For example, if variables b1 and b2 are of byte type, while i1 is of int type, will b1 and b2 get converted to int prior to computing (b1+b2):

int i2=(b1+b2)+i1
like image 212
flockofcode Avatar asked Jun 20 '10 19:06

flockofcode


1 Answers

The parentheses are of higher precedence than +, so the conversion would normally take place after b1 and b2 have been added. However, the + operator does not have an overload for bytes, so the bytes must first be promoted to ints.

Further reading:

  • operator precedence
  • binary numeric promotion
like image 160
Kent Boogaart Avatar answered Oct 26 '22 22:10

Kent Boogaart