I am not at a computer so cannot test this at the moment but have some code to review. I'm still somewhat in a C++ mindframe unfortunatley.
So, when a typedef is declared within a C source file what is its scope? I am aware that to make functions and variables only available within the same translation unit you need to make them static and I was wondering if this is the same for typedefs?
typedef is a reserved keyword in the programming languages C and C++. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.
The C language contains the typedef keyword to allow users to provide alternative names for the primitive (e.g., int) and user-defined (e.g struct) data types. Remember, this keyword adds a new name for some existing data type but does not create a new type.
The typedef keyword allows the programmer to create new names for types such as int or, more commonly in C++, templated types--it literally stands for "type definition". Typedefs can be used both to provide more clarity to your code and to make it easier to make changes to the underlying data types that you use.
typedef is limited to giving symbolic names to types only, whereas #define can be used to define an alias for values as well, e.g., you can define 1 as ONE, 3.14 as PI, etc. typedef interpretation is performed by the compiler where #define statements are performed by preprocessor.
Here is an example showing typedef and scope:
typedef int foo_t;
foo_t x = 1;
double bar(double x) {
typedef double foo_t;
foo_t y = 2.0;
return y + 3.14156;
}
foo_t z = 1;
Typedefs are declarations. If you have a typedef in a C file, no other C file will be aware of that since they are compiled indepedendly of each other.
For a typedef in a header, it will of course be visible from all C files that include it.
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