I came across an expression in C like
typeof((c) + 1) _tmp = c;
What exactly does this mean?
Thanks for the reply.
Just one doubt? What if the type of c is struct instead of the primitive types, then what will +1 do?
The typeof keyword is a new extension to the C language. The Oracle Developer Studio C compiler accepts constructs with typeof wherever a typedef name is accepted, including the following syntactic categories: Declarations. Parameter type lists and return types in a function declarator. Type definitions.
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.
The typeof is an operator keyword which is used to get a type at the compile-time. Or in other words, this operator is used to get the System. Type object for a type.
The operator returns the data type. There are six possible values that typeof returns: object, boolean, function, number, string, and undefined. The following table summarizes possible values returned by the typeof operator.
The typeof
operator in plain C (not C++) is a GCC addition to the standard. It tells the compiler you want to use the type of the expression enclosed in parenthesis.
Using typeof
as above, you can declare variables of types unknown to you or in that context, using another variable's type as reference. It can also be used for casting.
The +
operation inside typeof
has a peculiar effect. typeof((c) + 1)
means "the type of c, or the type of 1, whichever would remain after promotion". Remember that, for example, chars are promoted to ints when used in operations involving ints, ints are promoted to floats, floats to doubles, etc.
So, typeof(int_variable + char_variable)
is int
, since the char
would be promoted to int
to perform the operation.
Note that only the compiler can resolve this: typeof
doesn't evaluate, it has no value, nothing happens at run-time.
The full description of typeof
can be found here.
create var _tmp
st _tmp
is of type upcast (max) of c
or int
and set it to value of c
.
eg
char c -> int _tmp // char(c) + 1 is int
float c -> float _tmp // float(c) + 1 is float
In addition to the other answer, the +
here is quite subtle. It allows for c
to be either an expression or a type.
c
is promoted to int
(at least)
and the type of the whole expression
has at least integer rank of int
.c
make it a
cast of the value +1
. So then the resulting type is just c
.For both kinds of acrobatic it is important that c
is of arithmetic type and it is also to note that this trick here might loose the signedness of c
. So this use of the typeof
extension is not so useful as it might look like. In most cases using uintmax_t
or intmax_t
would be sufficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With