Home > Backend Development > C++ > What's the Key Difference Between `typedef` and `using` for Type Aliases in C ?

What's the Key Difference Between `typedef` and `using` for Type Aliases in C ?

Barbara Streisand
Release: 2024-12-25 20:27:09
Original
545 people have browsed it

What's the Key Difference Between `typedef` and `using` for Type Aliases in C  ?

Understanding the Nuances of 'typedef' and 'using' in C

The 'typedef' and 'using' keywords in C both facilitate the creation of type aliases. While they serve similar purposes, subtle differences exist in their implementation.

In C 11 and onwards, the 'using' syntax emerged as a concise way to define type aliases. For example:

using MyInt = int;
Copy after login

This is semantically equivalent to the traditional 'typedef':

typedef int MyInt;
Copy after login

However, the 'using' syntax gained prevalence due to its ability to express "template typedefs":

template<class T> using MyType = AnotherType<T, MyAllocatorType>;
Copy after login

Now, let's explore potential differences between 'typedef' and 'using' regarding alias strength. 'typedef' is known for its "weak" aliasing behavior, meaning it doesn't create a new type but merely establishes a new name. Conversions between aliased types and their original types are implicit.

The question arises: does 'using' behave similarly or does it result in the creation of a new type? The answer, as per the C Standard (7.1.3.2), is that they are equivalent in semantics:

"It [using] has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id."
Copy after login

Therefore, both 'typedef' and 'using' create weak aliases without generating new types, resulting in implicit conversions between aliased and original types.

The above is the detailed content of What's the Key Difference Between `typedef` and `using` for Type Aliases in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template