You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm unsure how deep the language reference is supposed to dig into the inner workings of the MCU.
I think in this case the issue with scope of the calculation is relevant, because it is a consequence of the rollover. For beginners, the easiest is to avoid unsigned variables alltogether :-)
Copy file name to clipboardExpand all lines: Language/Variables/Data Types/unsignedInt.adoc
+26-1Lines changed: 26 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -61,7 +61,32 @@ unsigned int x;
61
61
x = x + 1; // x now contains 0 - rolls over
62
62
----
63
63
64
+
Math with unsigned variables may produce unexpected results, even if your unsigned variable never rolls over.
64
65
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.
0 commit comments