Skip to content

Commit 3c464bc

Browse files
author
SimonePDA
authored
Merge pull request arduino#304 from hydrocontrol/patch-2
Update unsignedInt.adoc
2 parents aa1904b + 4d3cb70 commit 3c464bc

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

Language/Variables/Data Types/unsignedInt.adoc

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,32 @@ unsigned int x;
6161
x = x + 1; // x now contains 0 - rolls over
6262
----
6363

64+
Math with unsigned variables may produce unexpected results, even if your unsigned variable never rolls over.
6465

66+
The MCU applies the following rules:
67+
68+
The calculation is done in the scope of the destination variable. E.g. if the destination variable is signed, it will do signed math, even if both input variables are unsigned.
69+
70+
However with a calculation which requires an intermediate result, the scope of the intermediate result is unspecified by the code. In this case, the MCU will do unsigned math for the intermediate result, because both inputs are unsigned!
71+
72+
73+
[source,arduino]
74+
----
75+
unsigned int x=5;
76+
unsigned int y=10;
77+
int result;
78+
79+
result = x - y; // 5 - 10 = -5, as expected
80+
result = (x - y)/2; // 5 - 10 in unsigned math is 65530! 65530/2 = 32765
81+
82+
// solution: use signed variables, or do the calculation step by step.
83+
result = x - y; // 5 - 10 = -5, as expected
84+
result = result / 2; // -5/2 = -2 (only integer math, decimal places are dropped)
85+
----
86+
Why use unsigned variables at all?
87+
88+
- The rollover behaviour is desired, e.g. counters
89+
- The signed variable is a bit too small, but you want to avoid the memory and speed loss of long/float.
6590
--
6691
// HOW TO USE SECTION ENDS
6792

@@ -77,4 +102,4 @@ unsigned int x;
77102
* #LANGUAGE# link:../../constants/integerconstants[Integer Constants]
78103

79104
--
80-
// SEE ALSO SECTION ENDS
105+
// SEE ALSO SECTION ENDS

0 commit comments

Comments
 (0)