Typedef c что это
Перейти к содержимому

Typedef c что это

  • автор:

Typedef c что это

The typedef is a keyword that is used in C programming to provide existing data types with a new name. typedef keyword is used to redefine the name already the existing name. When names of datatypes become difficult to use in programs, typedef is used with user-defined datatypes, which behave similarly to defining an alias for commands.

Syntax:

Example:

Below is the C program to implement typedef:

Applications of typedef

  • The typedef keyword gives a meaningful name to the existing data type which helps other users to understand the program more easily.
  • It can be used with structures to increase code readability and we don’t have to type struct again and again.
  • The typedef keyword can also be used with pointers to declare multiple pointers in a single statement.
  • It can be used with arrays to declare any number of variables.

1. Using typedef with structures

typedef can also be used with structures in the C programming language. A new data type can be created and used to define the structure variable.

Below is the C program to implement typedef with structures:

2. Using typedef with pointers

typedef can also be used with pointers as it gives an alias name to the pointers. Typedef is very efficient while declaring multiple pointers in a single statement because pointers bind to the right on the simple declaration.

Example:

In the above statement var, var1, and var2 are declared as pointers of type int which helps us to declare multiple numbers of pointers in a single statement.

# Typedef

The typedef mechanism allows the creation of aliases for other types. It does not create new types. People often use typedef to improve the portability of code, to give aliases to structure or union types, or to create aliases for function (or function pointer) types.

In the C standard, typedef is classified as a ‘storage class’ for convenience; it occurs syntactically where storage classes such as static or extern could appear.

# Typedef for Structures and Unions

You can give alias names to a struct :

Compared to the traditional way of declaring structs, programmers wouldn’t need to have struct every time they declare an instance of that struct.

Note that the name Person (as opposed to struct Person ) is not defined until the final semicolon. Thus for linked lists and tree structures which need to contain a pointer to the same structure type, you must use either:

The use of a typedef for a union type is very similar.

A structure similar to this can be used to analyze the bytes that make up a float value.

# Simple Uses of Typedef

# For giving short names to a data type

This reduces the amount of typing needed if the type is used many times in the program.

# Improving portability

The attributes of data types vary across different architectures. For example, an int may be a 2-byte type in one implementation and an 4-byte type in another. Suppose a program needs to use a 4-byte type to run correctly.

In one implementation, let the size of int be 2 bytes and that of long be 4 bytes. In another, let the size of int be 4 bytes and that of long be 8 bytes. If the program is written using the second implementation,

For the program to run in the first implementation, all the int declarations will have to be changed to long .

To avoid this, one can use typedef

Then, only the typedef statement would need to be changed each time, instead of examining the whole program.

The <stdint.h> header and the related <inttypes.h> header define standard type names (using typedef ) for integers of various sizes, and these names are often the best choice in modern code that needs fixed size integers. For example, uint8_t is an unsigned 8-bit integer type; int64_t is a signed 64-bit integer type. The type uintptr_t is an unsigned integer type big enough to hold any pointer to object. These types are theoretically optional — but it is rare for them not to be available. There are variants like uint_least16_t (the smallest unsigned integer type with at least 16 bits) and int_fast32_t (the fastest signed integer type with at least 32 bits). Also, intmax_t and uintmax_t are the largest integer types supported by the implementation. These types are mandatory.

# To specify a usage or to improve readability

If a set of data has a particular purpose, one can use typedef to give it a meaningful name. Moreover, if the property of the data changes such that the base type must change, only the typedef statement would have to be changed, instead of examining the whole program.

# Typedef for Function Pointers

We can use typedef to simplify the usage of function pointers. Imagine we have some functions, all having the same signature, that use their argument to print out something in different ways:

Now we can use a typedef to create a named function pointer type called printer:

This creates a type, named printer_t for a pointer to a function that takes a single int argument and returns nothing, which matches the signature of the functions we have above. To use it we create a variable of the created type and assign it a pointer to one of the functions in question:

Then to call the function pointed to by the function pointer variable:

Thus the typedef allows a simpler syntax when dealing with function pointers. This becomes more apparent when function pointers are used in more complex situations, such as arguments to functions.

If you are using a function that takes a function pointer as a parameter without a function pointer type defined the function definition would be,

However, with the typedef it is:

Likewise functions can return function pointers and again, the use of a typedef can make the syntax simpler when doing so.

A classic example is the signal function from <signal.h> . The declaration for it (from the C standard) is:

That’s a function that takes two arguments — an int and a pointer to a function which takes an int as an argument and returns nothing — and which returns a pointer to function like its second argument.

If we defined a type SigCatcher as an alias for the pointer to function type:

then we could declare signal() using:

On the whole, this is easier to understand (even though the C standard did not elect to define a type to do the job). The signal function takes two arguments, an int and a SigCatcher , and it returns a SigCatcher — where a SigCatcher is a pointer to a function that takes an int argument and returns nothing.

Although using typedef names for pointer to function types makes life easier, it can also lead to confusion for others who will maintain your code later on, so use with caution and proper documentation. See also Function Pointers

# Syntax
  • typedef existing_name alias_name;
# Remarks

Disadvantages of Typedef

typedef could lead to the pollution of namespace in large C programs.

Disadvantages of Typedef Structs

Also, typedef ‘d structs without a tag name are a major cause of needless imposition of ordering relationships among header files.

With such a definition, not using typedefs , it is possible for a compilation unit to include foo.h to get at the FOO_DEF definition. If it doesn’t attempt to dereference the bar member of the foo struct then there will be no need to include the bar.h file.

Typedef vs #define

#define is a C pre-processor directive which is also used to define the aliases for various data types similar to typedef but with the following differences:

Зачем нужен typedef?

typedef используется для создания псевдонимов других типов данных. Приведенный пример лучше скорректировать, например:

typedef может использоваться не только для структур, но и для любых других типов:

Основные причины использования typedef -объявлений

Сокращение имен типов данных для улучшения читабельности и простоты набора кода. В приведенном примере без использования typedef придется писать struct LINE . В C++ эта проблема решена (можно просто писать LINE ), однако могут использоваться длинные названия типов, например: std::vector<LINE>::size_type может быть сокращено с помощью typedef . t_lvecsz .

Абстрагирование от используемого в данной реализации типа данных для облегчения возможных изменений реализации. Например, struct LINE может быть объявлено так:

и во всем остальном коде для представления координат использоваться тип float . При возникновении необходимости перехода, например, к типу double потребуется вносить множество изменений в код (и, как всегда, где-то забыть внести изменения). Эта проблема хорошо решается с помощью следующих объявлений:

Также typedef может использоваться для облегчения создания объявлений сложных типов (что-то вроде «массив указателей на функции, возвращающие указатель на структуру и т.д.»).

typedef specifier

The typedef specifier, when used in a declaration, specifies that the declaration is a typedef declaration rather than a variable or function declaration. Typically, the typedef specifier appears at the start of the declaration, though it is permitted to appear after the type specifiers, or between two type specifiers.

A typedef declaration may declare one or many identifiers on the same line (e.g. int and a pointer to int), it may declare array and function types, pointers and references, class types, etc. Every identifier introduced in this declaration becomes a typedef-name, which is a synonym for the type of the object or function that it would become if the keyword typedef were removed.

The typedef specifier cannot be combined with any other specifier except for type-specifiers.

The typedef-names are aliases for existing types, and are not declarations of new types. 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 names are only in effect in the scope where they are visible: different functions or class declarations may define identically-named types with different meaning.

The typedef specifier may not appear in the declaration of a function parameter nor in the decl-specifier-seq of a function definition:

The typedef specifier may not appear in a declaration that does not contain a declarator:

[edit] typedef-name for linkage purposes

Formally, if the typedef declaration defines an unnamed class or enum, the first typedef-name declared by the declaration to be that class type or enum type is used to denote the class type or enum type for linkage purposes only. For example, in typedef struct { /* . */ } S ; , S is a typedef-name for linkage purposes. The class or enum type defined in this way has external linkage (unless it’s in an unnamed namespace).

An unnamed class defined in this way should only contain C-compatible constructs. In particular, it must not

  • declare any members other than non-static data members, member enumerations, or member classes,
  • have any base classes or default member initializers, or
  • contain a lambda-expression,

and all member classes must also satisfy these requirements (recursively).

[edit] Keywords

[edit] Notes

type aliases provide the same functionality as typedefs using a different syntax, and are also applicable to template names.

[edit] Example

[edit] Defect Reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *