Why aren't typedefs strongly typed?
Asked Answered
S

3

6

What's the reason for typedefs not being strongly typed? Is there any benefit I can't see or is it due to backward compatibility? See this example:

typedef int Velocity;
void foo(Velocity v) {
    //do anything;
}
int main() {
    int i=4;
    foo(i); //Should result in compile error if strongly typed.
    return 0;
}

I am not asking for workarounds to get a strong typed datatype but only want to know why the standard isn't requiring typedefs to be strongly typed?

Thank you.

Scarabaeus answered 18/11, 2011 at 13:9 Comment(3)
Because C is a language for people who want to Get Things Done, not for people who want to Ponder the Mathematical Beauty of Abstract Type Systems. (As someone who appreciates both activities, I'm not judging either one).Calandra
@Stephen Canon: Who says Abstract Type Systems can't help you to Get Things Done? Debugging runtime errors that result from accidentally misused types certainly doesn't count as Getting Things Done in my book.Bicentennial
@MichaelBorgwardt: I certainly didn't say that they can't. However, they can be abused.Calandra
S
14

Because C is not strongly typed and typedef has its origin in that thinking

typedef is just for convenience and readability, it doesn't create a new type.

Solberg answered 18/11, 2011 at 13:12 Comment(0)
M
4

typedef is just a missnomer (like many other keywords). Think of it as typealias.

C has in the contrary a whole idea of what compatible types are. This allows for example to link compilation units together, even if declarations of function protopyes are only done with compatible types and not with identical ones. All this comes from simple practical necessity in every day life, being still able to give some guarantees to implementations.

Molnar answered 18/11, 2011 at 13:33 Comment(2)
Isn't the main idea of C really "It's all just bits, let's not hide that too much"?Bicentennial
@MichaelBorgwardt, no I don't think so. Otherwise it wouldn't have this detailed model of compatible types.Molnar
B
0

Even if Velocity were a distinct type from int, your code would compile and work just fine due to type conversion rules. What would not work is passing an expression of type Velocity * to a function expecting int *, etc. If you want to achieve the latter form of type enforcement, simply make Velocity a structure or union type containing a single integer, and you'll now have a new real type.

Bluejacket answered 18/11, 2011 at 14:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.