Is it good practice to use typedef for putting units of measurement into name? (and rename standard types) Like this:
typedef int16_t MilliAmp_t; /* 1 mA */
You are just renaming some types. It does not bring any additional checks in the compiler (unless that compiler is customized specifically; if using GCC you could consider customizing it thru MELT, but that customization is not a trivial task), in the sense that the following code
MilliAmp_t x=0,y=1,z=2;
x = y * z;
will always compile without warnings (in C) even if physically multiplying two currents and put the result in some current variable does not make any sense.
However, your typedef has a small documentation value: if you declare a prototype like
MilliWatt_t electical_power (MilliAmp_t current, MilliVolt_t tension);
then some readers might find that helpful (but perhaps not me).
Yes, such typedefs are fairly common. Although C doesn't provide for strong typing that would prevent you from assigning a current quantity to a voltage variable, such a practice does allow you to see at a glance what a variable means without encoding that information into the name.
When I've personally written physical analysis code for small microcontrollers, I prefer to pick the range more carefully than just "1 step = 1 milliamp," so as to maximize precision. So, I'd prefer just voltage_t
and current_t
, and then use global conversion coefficients when relating them to known physical quantities.
Overflow and precision loss are important considerations when doing physical math with integers. Keeping variables in proper physical units tends to help keep intermediate results in a proper dynamic range, thus avoiding these problems, as long as the physical system keeps its voltages and currents within the range that you've chosen for uniform computational use.
If you have an FPU, I'd recommend using that, and don't bother with SI prefixes because it will handle milli-, micro-, and anything else transparently without mucking about with coefficients. Using typedef double amps;
will still help code equations in a reasonable and expository way, and you can easily adjust the precision of the entire program later. By all means, do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With