I've encountered the following code:
typedef int var[1]; // or var[3]
what does it actually do? I don't understand what does the subscript add, since now I can define "var" for int
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.
A typedef declaration is a declaration with typedef as the storage class. The declarator becomes a new type. You can use typedef declarations to construct shorter or more meaningful names for types already defined by C or for types that you have declared.
typedef is used to define new data type names to make a program more readable to the programmer. For example: | main() | main() { | { int money; | typedef int Pounds; money = 2; | Pounds money = 2 } | } These examples are EXACTLY the same to the compiler.
Typedef cannot be used to change the meaning of an existing type name (including a typedef-name). Once declared, a typedef-name may only be redeclared to refer to the same type again.
typedef
declarations use the same syntax as ordinary variable declarations. The difference is that instead of declaring "a variable named x
of type y
," you declare "a type named x
that is a synonym for type y
." The syntax is otherwise the same.
So, let's remove the typedef
from your example and see what we get:
int var[1];
var
is a variable whose type is int[1]
, or, an array of one int
. If we add the typedef
back:
typedef int var[1];
this makes var
a synonym for the type int[1]
.
The same works for other kinds of ugly or complex types:
int (*fp)(int); // fp is a function pointer variable
typedef int (*fp)(int); // fp is a function pointer type
You can avoid most of this confusion by using an identity
template, declared as
template <typename T> struct identity { typedef T type; };
Using this template, the meaning of a complex type or variable declaration is much clearer. For example, we can declare our types like so:
typedef identity<int[1] >::type var; // array type
typedef identity<int(*)(int)>::type fp; // function pointer type
and because variable declarations use the same syntax as type declarations, we can declare variables that have a complex using identity
as well:
identity<int[1] >::type var; // array variable
identity<int(*)(int)>::type fp; // function pointer variable
var
is a type definition for an int
array of size one.
You can write
var x;
and x
will be a variable of type int[1]
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