Question

typedef int A;
typedef int B;

void foo(A arg){}

void main(void){
    B wrongvar = 7;
    foo(wrongvar);
}

Is this construction supposed to return a warning/error, according to the standard? What about the most popular compilers?

Example: we have variables, representing kilograms and meters, and all are type 'int'. We have a function, processing meters. We want the compiler to catch bugs, related to passing kilograms meaning variables variables to that function.

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

Was it helpful?

Solution

No, what you're dealing with is a type discipline issue known as structural equivalence vs name equivalence. As Dog said, the closest thing you could do to achieve what you want is use structs, but this could be a waste of memory if the compiler chooses to add padding (which in this case is unlikely). C uses structural equivalence (meaning the two types are the same thing) for aliases, but name equivalence for different declared structs (two struct types with the same layout are not treated as equivalent).

An example of using structs to do 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 may wish to read this article: http://www.joelonsoftware.com/articles/Wrong.html describing how you can help avoid these issues with naming conventions

OTHER TIPS

You could use a struct with one field to do exactly what you want. The only "downside" is that you'll potentially waste 1/2/4/8 bytes if the optimizer doesn't optimize them out...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top