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?
Typedefs provide a level of abstraction away from the actual types being used, allowing you, the programmer, to focus more on the concept of just what a variable should mean. This makes it easier to write clean code, but it also makes it far easier to modify your code.
The major limitation of typedef is that it does not work with templates. Both using and typedef perform the same mechanically while working with non-templates. However, while defining the more complex template aliases, function-pointer aliases, and array reference aliases, the using statement emerges as a clear winner.
typedef is used to define new data type names to make a program more readable to the programmer. These examples are EXACTLY the same to the compiler. But the right hand example tells the programmer the type of money he is dealing with. A common use for typedef is to define a boolean data type as below.
You can use typedef to give a name to your user defined data types as well. For example, you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows −
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
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With