Why is Stateflow Coder up-casting variables from uint8 to uint32?
2 views (last 30 days)
Show older comments
Simple Stateflow chart using MATLAB language (one-based indexing).
Variable 'j' is a uint8 defined in Model Explorer.
My Stateflow loop uses the following as a loop counter:
j = j + uint8(1);
Sateflow Coder produces the following code:
for (j = 1U; j < ((uint8_t)(TCF_DWork.NumberOfPoints + 1U)); j = (uint8_t)((int32_t)(((int32_t)j) + ((int32_t)1))))
Why is Stateflow Code up-casting to uint32 before the increment? I only see this on Stateflow charts within a Simulink model.
I am using ARM9 Compatible 32-bit target. Could this be causing the up-casting? I remember changing the target type to a Generic 8-bit processor and still saw the same issue.
0 Comments
Answers (1)
James Tursa
on 12 Jul 2016
Edited: James Tursa
on 12 Jul 2016
In the C language, the "usual arithmetic conversions" are applied automatically to operands of many unary and binary operations, and in particular the + operation. E.g., if you had these definitions in C:
unsigned char i = 1, j = 2, k; // <-- Assume chars are 8-bit integers
Then this code:
k = i + j;
actually gets compiled as the equivalent of:
k = (unsigned char)((int)i + (int)j);
I.e., the 8-bit unsigned char's get up-converted automatically to int's and the + is actually done with int's. Then the result is down-converted to unsigned char for assignment. This happens automatically and is part of the language. E.g., the result of this mex code:
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
unsigned char a = 200, b = 200, c;
c = a + b;
mexPrintf("sizeof(a) = %d\n",sizeof(a));
mexPrintf("sizeof(b) = %d\n",sizeof(b));
mexPrintf("sizeof(a+b) = %d\n",sizeof(a+b));
mexPrintf("a+b = %d\n",a+b);
mexPrintf("c = %d\n",c);
}
is:
sizeof(a) = 1
sizeof(b) = 1
sizeof(a+b) = 4
a+b = 400
c = 144
So you can see that the result of the + operation is actually a 4-byte integer even though the operands are 1-byte integers, which matches expectations from the C language specs. The value printed out (400) actually overflows an unsigned char (max 255), but that conversion doesn't happen until the assignment (resulting in 144).
I am not that familiar with Stateflow, but it could be that the Stateflow Code is simply making these automatic up and down conversions explicit in the C source. Unless there is some reason to make these counters 8-bit, why not just make them 32-bit and save yourself from all of those unnecessary conversions?
0 Comments
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!