c - Using 'typedef' to ensure logical type safety -


typedef int a; typedef int b;  void foo(a arg){}  void main(void){     b wrongvar = 7;     foo(wrongvar); } 

is construction supposed return warning/error, according standard? popular compilers?

example: have variables, representing kilograms , meters, , type 'int'. have function, processing meters. want compiler catch bugs, related passing kilograms meaning variables variables function.

i believe ada handles smoothly. modern c?

no, you're dealing type discipline issue known structural equivalence vs name equivalence. dog said, closest thing achieve want use structs, waste of memory if compiler chooses add padding (which in case unlikely). c uses structural equivalence (meaning 2 types same thing) aliases, name equivalence different declared structs (two struct types same layout not treated equivalent).

an example of using structs 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 kilos     return 0; } 

you may wish read article: http://www.joelonsoftware.com/articles/wrong.html describing how can avoid these issues naming conventions


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -