Assignment and datatypes
General information
Assignment is not part of expression evaluation. In an assignment
statement, the value of an expression is converted to the datatype
of the left-hand variable. In the expression
|
1 |
c = a + b |
the datatype of a+b is
determined by the datatypes of a and b.
Then, the result is converted to the datatype of c.
Overflow on assignment
Even when PowerBuilder performs a calculation at high enough
precision to handle the results, assignment to a lower precision
variable can cause overflow, producing the wrong result.
Example 1
Consider this code:
|
1 |
integer a = 32000, b = 1000 |
|
1 |
long d |
|
1 |
d = a + b |
The final value of d is 33000. The calculation
proceeds like this:
-
Convert
integer a to long -
Convert integer b to long
-
Add the longs a and b
-
Assign the result to the long d
Because the variable d is a long,
the value 33000 does not cause overflow.
Example 2
In contrast, consider this code with an assignment to an integer variable:
|
1 |
integer a = 32000, b = 1000, c |
|
1 |
long e |
|
1 |
c = a + b |
|
1 |
e = c |
The resulting value of c and e is
-32536. The calculation proceeds like this:
-
Add the integers a and b
-
Assign the result to c
-
Convert integer c to long and
assign the result to e
The assignment to the integer variable c causes
the long result of the addition to be truncated, causing overflow
and wrapping. Assigning c to e cannot restore
the lost information.