Using "typedef" to ensure logical type security

typedef int A; typedef int B; void foo(A arg){} void main(void){ B wrongvar = 7; foo(wrongvar); } 

Is this design supposed to return a warning / error in accordance with the standard? What about the most popular compilers?

Example: we have variables representing kilograms and meters, and all this is of type 'int'. We have a function, processing counters. We want the compiler to detect errors related to the transfer of kilograms meaning variable variables for this function.

I believe Ada handles this smoothly. What about modern C?

+7
source share
2 answers

No, what you are dealing with is a discipline type problem known as structural equivalence and name equivalence. As Dog said, the closest thing you could do to achieve what you want is to use structures, but it can be a waste of memory if the compiler decides to add an add-on (which is unlikely in this case). C uses structural equivalence (which means the two types are the same) for aliases, but name equivalence for different declared structures (two types of structures with the same layout are not considered equivalent).

An example of using structures for this:

 typedef struct { double value; } meters; typedef struct { double value; } kilograms; int main(){ meters m; kilograms k = {2}; // initialized m.value = 1; k = m; // error, can't assign meters to kilos return 0; } 

You can read this article: http://www.joelonsoftware.com/articles/Wrong.html , describing how you can avoid these problems with naming conventions

+7
source

You can use a single field structure to do exactly what you want. The only drawback is that you can potentially spend 2/4/8 bytes if the optimizer does not optimize them ...

+2
source

All Articles