typeof operator in C

CGccTypeof

C Problem Overview


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)?

C Solutions


Solution 1 - C

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.

Solution 2 - C

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.

Solution 3 - C

It is a C extension from the GCC compiler , see http://gcc.gnu.org/onlinedocs/gcc/Typeof.html

Solution 4 - C

It's not exactly an operator, rather a keyword. And no, it doesn't do any runtime-magic.

Solution 5 - C

One case in which you will need to use this extension is to get the pointer of an anonymous structs. You can check this this question for an example.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDougView Question on Stackoverflow
Solution 1 - CJens GustedtView Answer on Stackoverflow
Solution 2 - CcnicutarView Answer on Stackoverflow
Solution 3 - CAndré OrianiView Answer on Stackoverflow
Solution 4 - Cuser529758View Answer on Stackoverflow
Solution 5 - Cوليد تاج الدينView Answer on Stackoverflow