Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typedef to put units of measurement in C

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 */
like image 542
artsin Avatar asked Jan 09 '23 02:01

artsin


2 Answers

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).

like image 52
Basile Starynkevitch Avatar answered Jan 20 '23 10:01

Basile Starynkevitch


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.

like image 43
Potatoswatter Avatar answered Jan 20 '23 08:01

Potatoswatter