Email: support@essaywriterpros.com
Call Us: US - +1 845 478 5244 | UK - +44 20 7193 7850 | AUS - +61 2 8005 4826

Institution of Analysts and Programmers

When this code is executed, you get the following error:

main.c: In function ‘my_func’:main.c:25:5: error: unknown type name ‘my_int’ my_int b = 20; ^

So as you can see, the compiler couldn’t recognize the type ‘my_int’ in the ‘my_func’ function, as the scope under which typedef was valid was the scope of the ‘main’ function.

Then there are some other differences between a typedef and a #define. Like, using a #define, you can also create aliases for constant values – I mean, you can do something like ‘#define PIE 3.14’. Also, as you’d have observed, a #define is not terminated by a semicolon while a typedef is. 

Now, one would still ask why we need ‘typedef’. Or in other words, where does a typedef comes in real handy? Well, suppose there’s a piece of code with functions that return ‘pointer to a function which accepts two integers as arguments as returns a character value’.

In case you aren’t aware, such a pointer is declared in the following way:

char (*fn_ptr) (int, int);

Where fn_ptr is the name of such a pointer.

So rather than having to use this kind of lengthy and complex declaration again and again as the return type of other functions, you can just make fn_ptr a type using typedef:

typedef char (*fn_ptr) (int, int);

And now you can just use ‘fn_ptr’, and it will signify a pointer of this type. 

Another use of typedef involves using in code a user-defined data type which corresponds to the native type provided by the underlying platform on which the code runs. This way, typedefs help make easy to understand and maintain any piece of code that’s developed to run on multiple platforms.