I would like the c compiler to check the usage of simple types. My preferred usage would be checking typedef
s, but that is not done even with -Wall
and -Wextra
:
#include <math.h>
#include <stdio.h>
typedef float deg;
typedef float rad;
float sinus( rad angle ) {
return sin( angle );
}
int main() {
deg a = 180;
printf( "The sinus of %g is %g\n", a, sinus(a));
return 0;
}
This compiles without a hitch.
So I'm considering using one-member structures:
#include <math.h>
#include <stdio.h>
typedef struct { float value; } deg;
typedef struct { float value; } rad;
float sinus( rad angle ) {
return sin( angle.value );
}
int main() {
deg a = {.value=180};
printf( "The sinus of %g is %g\n", a, sinus(a));
return 0;
}
This gives an outright error (as it should). However, I'm wondering about the performance. If I correct the above examples, the produced binaries have the same size, with optimization or without. However, the produced assembly differs. Can the compiler optimize out the struct
, even in more complicated contexts? If not, is there another way to achieve type-safety for primitive types?
I'm using GCC (9.1.0), but I'd consider llvm if that helps. This is supposed to work for common desktop architectures, i.e. x86, x86_64, ARM.
Edit: I noticed you could also use union
instead of struct
in the above example. This again produces slightly different assembly code and again I'm not clear on the real world performance consequences.
gcc -Wall -Wextra -O3 -flto
?-Wextra
does not help. The change log for GCC 10 does not mention warnings for typedefs.