Search code examples
ctypestypedefada

Difference between typedef in C and application-defined types in Ada


So I was learning about application-defined types in Ada and it seems like typedef in C programming language. However, if I created a new name for a predefined type in C using typedef I can still do this:

typedef int my_int;
int a = 5;
my_int b = a; -- No problem

But if I try this on Ada:

type my_int is new Integer;
a : Integer := 5;
b : my_int  := a; -- Causes some error

So my question is that is my understanding correct that in C my_int is just an alias or a new name of type int and not a new type whereas in Ada my_int is a completely different data type itself not just a new name for type Integer.


Solution

  • The first, declaring type in Ada isn't that same as typedef in C. typedef is more like creating an alias of an existing simple type. The proper way in Ada to do this is to declare a type as subtype. In your example it should be (as Zerte suggested in comments):

    subtype my_int is Integer;
    

    In that situation your code will work. Side note: creating records in Ada is very similar to creating structures in C with typedef.

    Ada is a very strongly typed language. A type can't be assigned to another type without a type conversion (called a "cast" in C-family languages). For example:

    type My_Int is new Integer;
    type My_Int2 is new Integer;
    

    Both types are incompatible with each other or with their parent type Integer, and if you want to mix them, you have to use type conversions.

    As someone who travelled from C to Ada land I think, the most important if you want to understand Ada, is to understand Ada types system. It is something completely different from C. C is more focused on manipulating data when Ada puts more emphasis on data representation.