Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typeof operator in C

Tags:

c

gcc

typeof

Is typeof in C, really an operator?
I'm thinking because there is no polymorphism in C, that there is nothing to do at run-time. That is, the answer to typeof is known at compile-time. (I can't think of a use of typeof that would not be known at compile time.) So it appears to be more of a compile-time directive, than an operator.

Does typeof use any (processor) run-time (in GCC)?

like image 521
Doug Avatar asked Aug 22 '12 21:08

Doug


People also ask

What does typeof () in C return?

In other languages, such as C# or D and, to some degree, in C (as part of nonstandard extensions and proposed standard revisions), 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.

What is __ typeof __ in C?

The __typeof__ operator returns the type of its argument, which can be an expression or a type. The language feature provides a way to derive the type from an expression. Given an expression e , __typeof__(e) can be used anywhere a type name is needed, for example in a declaration or in a cast.

Is typeof an operator?

The typeof operator is not a variable. It is an operator. Operators ( + - * / ) do not have any data type. But, the typeof operator always returns a string (containing the type of the operand).

Is typeof in standard C?

typeof is a extension featured in many implementations of the C standard to get the type of an expression. It works similarly to sizeof , which runs the expression in an “unevaluated context” to understand the final type, and thusly produce a size.


2 Answers

Since typeof is a compiler extension, there is not really a definition for it, but in the tradition of C it would be an operator, e.g sizeof and _Alignof are also seen as an operators.

And you are mistaken, C has dynamic types that are only determined at run time: variable modified (VM) types.

size_t n = strtoull(argv[1], 0, 0); double A[n][n]; typeof(A) B; 

can only be determined at run time.

Add on in 2021: there are good chances that typeof with similar rules as for sizeof will make it into C23.

like image 89
Jens Gustedt Avatar answered Oct 03 '22 19:10

Jens Gustedt


It's a GNU extension. In a nutshell it's a convenient way to declare an object having the same type as another. For example:

int x;         /* Plain old int variable. */ typeof(x) y;   /* Same type as x. Plain old int variable. */ 

It works entirely at compile-time and it's primarily used in macros. One famous example of macro relying on typeof is container_of.

like image 28
cnicutar Avatar answered Oct 03 '22 20:10

cnicutar