Typeof
Typeof
Main page

Typeof

logo
Community Hub0 subscribers
What are your thoughts?
Be the first to start a discussion here.
Be the first to start a discussion here.
Typeof

typeof, alternately also typeOf, and TypeOf, is an operator provided by several programming languages to determine the data type of a variable. This is useful when constructing programs that must accept multiple types of data without explicitly specifying the type.

In languages that support polymorphism and type casting, the typeof operator may have one of two distinct meanings when applied to an object. In some languages, such as Visual Basic, the typeof operator returns the dynamic type of the object. That is, it returns the true, original type of the object, irrespective of any type casting. In these languages, the typeof operator is the method for obtaining run-time type information.

In other languages, such as C# or D and, in C (as of C23), the typeof operator returns the static type of the operand. That is, it evaluates to the declared type at that instant in the program, irrespective of its original form. These languages usually have other constructs for obtaining run-time type information, such as typeid.

Such an operator may be usable as a value, providing a run-time representation of the type, or as a type itself that can be applied to a value.

As of C23 typeof is a part of the C standard. The operator typeof_unqual was also added which is the same as typeof, except it removes cvr-qualification and atomic qualification (differentiating it from decltype in C++).

typeof can be useful for binding to variables of unknown type in macros. In this example, max must use temporary variables to avoid the inputs being evaluated multiple times, and uses typeof to specify the type of these temporary variables. Note that this example uses a non-standard extension to the C language, namely the use of compound statements as expressions (supported e.g. by GNU GCC)

C++ provides the decltype and typeid operators. decltype, like C’s typeof, is used to abbreviate types and to give types to variables that depend on the type of generic variables, whose type is unknown (e.g. in templates or macros). typeid provides a run-time representation of the type for dynamic dispatch.

The ^^ reflection operator, introduced in C++26, can also be used to obtain a representation of a type as a value.

See all
User Avatar
No comments yet.