What is the difference between “typedef” and “]using” in C++?
What is the difference between “typedef” and “]using” in C++?
379
07-Jul-2023
Updated on 10-Jul-2023
Aryan Kumar
10-Jul-2023The
typedefandusingkeywords in C++ are both used to create aliases for data types. However, there are some key differences between the two keywords.typedefdefines a new type, whileusingcreates an alias for an existing type. This means that you can use atypedefto declare variables, while you can only use ausingto refer to a variable that has already been declared using atypedefor ausing.typedefcan be used to create aliases for any type, whileusingcan only be used to create aliases for user-defined types. This means that you cannot use ausingto create an alias for a built-in type, such asintorfloat.typedefdeclarations are hoisted, whileusingdeclarations are not. This means that thetypedefdeclarations are evaluated at the top of the scope in which they are declared, while theusingdeclarations are evaluated at the point where they are encountered.In general, you should use
typedefif you want to define a new type that you will be using frequently. You should useusingif you want to refer to an existing type without having to write out the full name of the type every time you want to use it.Here are some examples of how to use
typedefandusing:C++
In both cases, the variable
pointand the variablemy_pointwill be of typePoint. However, the first code defines a new type calledPoint, while the second code simply creates an alias for the existing typestruct Point.The
usingdeclaration in the second code is not hoisted, which means that theMyPointalias is not evaluated until the point where it is encountered. This can lead to some unexpected behavior, so it is generally recommended to usetypedefinstead ofusingif you want to define a new type.